@imgly/plugin-ai-text-generation-web 0.2.4 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +12 -4
- package/dist/anthropic/index.mjs +9 -9
- package/dist/anthropic/index.mjs.map +3 -3
- package/dist/index.mjs +15 -15
- package/dist/index.mjs.map +3 -3
- package/dist/open-ai/index.mjs +11 -11
- package/dist/open-ai/index.mjs.map +4 -4
- package/dist/quickActions/ChangeTextTo.d.ts +1 -0
- package/dist/quickActions/ChangeTone.d.ts +1 -0
- package/dist/quickActions/Fix.d.ts +1 -0
- package/dist/quickActions/Improve.d.ts +1 -0
- package/dist/quickActions/Longer.d.ts +1 -0
- package/dist/quickActions/Shorter.d.ts +1 -0
- package/dist/quickActions/Translate.d.ts +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.2.5] - 2025-09-03
|
|
6
|
+
|
|
7
|
+
### New Features
|
|
8
|
+
|
|
9
|
+
- [image-generation] **NanoBanana Provider**: Added NanoBanana text-to-image provider via fal.ai with fast generation times, 1024×1024 resolution, support for multiple output formats (JPEG, PNG), configurable number of images (1-4), and remixPageWithPrompt quick action
|
|
10
|
+
- [image-generation] **NanoBananaEdit Provider**: Added NanoBananaEdit image-to-image provider via fal.ai for editing existing images with text prompts, supporting all standard quick actions (editImage, swapBackground, styleTransfer, artistTransfer, createVariant, combineImages with up to 10 images, remixPage, remixPageWithPrompt)
|
|
11
|
+
|
|
12
|
+
### Bug Fixes
|
|
13
|
+
|
|
14
|
+
- [all] **fal.ai Provider Configuration**: Fixed singleton configuration conflict when using multiple fal.ai providers with different proxy URLs. Each provider now maintains its own client instance instead of overwriting a global configuration
|
|
15
|
+
- [video-generation] **Missing Dependency**: Added missing `@fal-ai/client` dependency to plugin-ai-video-generation-web package.json to ensure the package works correctly when installed independently
|
|
16
|
+
|
|
5
17
|
## [0.2.4] - 2025-08-07
|
|
6
18
|
|
|
7
19
|
### New Features
|
package/README.md
CHANGED
|
@@ -252,12 +252,17 @@ cesdk.i18n.setTranslations({
|
|
|
252
252
|
|
|
253
253
|
#### QuickAction Translations
|
|
254
254
|
|
|
255
|
-
Text QuickActions (like "Improve Writing", "Fix Grammar", etc.) use their own translation keys:
|
|
255
|
+
Text QuickActions (like "Improve Writing", "Fix Grammar", etc.) use their own translation keys with provider-specific overrides:
|
|
256
256
|
|
|
257
257
|
```typescript
|
|
258
258
|
cesdk.i18n.setTranslations({
|
|
259
259
|
en: {
|
|
260
|
-
//
|
|
260
|
+
// Provider-specific translations (highest priority)
|
|
261
|
+
'ly.img.plugin-ai-text-generation-web.anthropic.quickAction.improve': 'Improve with Claude',
|
|
262
|
+
'ly.img.plugin-ai-text-generation-web.anthropic.quickAction.fix': 'Fix with Claude',
|
|
263
|
+
'ly.img.plugin-ai-text-generation-web.openai.quickAction.translate': 'Translate with GPT',
|
|
264
|
+
|
|
265
|
+
// Generic plugin translations
|
|
261
266
|
'ly.img.plugin-ai-text-generation-web.quickAction.improve': 'Improve Writing',
|
|
262
267
|
'ly.img.plugin-ai-text-generation-web.quickAction.fix': 'Fix Grammar',
|
|
263
268
|
'ly.img.plugin-ai-text-generation-web.quickAction.shorter': 'Make Shorter',
|
|
@@ -270,14 +275,17 @@ cesdk.i18n.setTranslations({
|
|
|
270
275
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt': 'Transform Text...',
|
|
271
276
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt.placeholder': 'e.g. "Convert to bullet points"',
|
|
272
277
|
'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.apply': 'Transform',
|
|
273
|
-
|
|
274
278
|
'ly.img.plugin-ai-text-generation-web.quickAction.translate.language': 'Target Language',
|
|
275
279
|
'ly.img.plugin-ai-text-generation-web.quickAction.translate.apply': 'Translate'
|
|
276
280
|
}
|
|
277
281
|
});
|
|
278
282
|
```
|
|
279
283
|
|
|
280
|
-
**QuickAction Translation
|
|
284
|
+
**QuickAction Translation Priority:**
|
|
285
|
+
1. Provider-specific: `ly.img.plugin-ai-text-generation-web.${provider}.quickAction.${action}.${field}`
|
|
286
|
+
2. Generic plugin: `ly.img.plugin-ai-text-generation-web.quickAction.${action}.${field}`
|
|
287
|
+
|
|
288
|
+
**Translation Structure:**
|
|
281
289
|
- Base key (e.g., `.quickAction.improve`): Button text when QuickAction is collapsed
|
|
282
290
|
- `.prompt`: Label for input field when expanded
|
|
283
291
|
- `.prompt.placeholder`: Placeholder text for input field
|
package/dist/anthropic/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Ur=typeof global=="object"&&global&&global.Object===Object&&global,rr=Ur,Br=typeof self=="object"&&self&&self.Object===Object&&self,Fr=rr||Br||Function("return this")(),C=Fr,zr=C.Symbol,K=zr,nr=Object.prototype,qr=nr.hasOwnProperty,Vr=nr.toString,ce=K?K.toStringTag:void 0;function Hr(r){var e=qr.call(r,ce),t=r[ce];try{r[ce]=void 0;var n=!0}catch{}var i=Vr.call(r);return n&&(e?r[ce]=t:delete r[ce]),i}var Gr=Hr,Wr=Object.prototype,Qr=Wr.toString;function Yr(r){return Qr.call(r)}var Kr=Yr,Jr="[object Null]",Xr="[object Undefined]",zt=K?K.toStringTag:void 0;function Zr(r){return r==null?r===void 0?Xr:Jr:zt&&zt in Object(r)?Gr(r):Kr(r)}var he=Zr;function en(r){return r!=null&&typeof r=="object"}var vt=en,Ms=Array.isArray;function tn(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var ir=tn,rn="[object AsyncFunction]",nn="[object Function]",on="[object GeneratorFunction]",sn="[object Proxy]";function an(r){if(!ir(r))return!1;var e=he(r);return e==nn||e==on||e==rn||e==sn}var ln=an,un=C["__core-js_shared__"],ht=un,qt=function(){var r=/[^.]+$/.exec(ht&&ht.keys&&ht.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function cn(r){return!!qt&&qt in r}var dn=cn,pn=Function.prototype,fn=pn.toString;function hn(r){if(r!=null){try{return fn.call(r)}catch{}try{return r+""}catch{}}return""}var U=hn,gn=/[\\^$.*+?()[\]{}|]/g,mn=/^\[object .+?Constructor\]$/,yn=Function.prototype,bn=Object.prototype,wn=yn.toString,xn=bn.hasOwnProperty,kn=RegExp("^"+wn.call(xn).replace(gn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vn(r){if(!ir(r)||dn(r))return!1;var e=ln(r)?kn:mn;return e.test(U(r))}var _n=vn;function An(r,e){return r?.[e]}var Sn=An;function Mn(r,e){var t=Sn(r,e);return _n(t)?t:void 0}var J=Mn,In=J(C,"WeakMap"),yt=In;function En(r,e){return r===e||r!==r&&e!==e}var Cn=En,Pn=9007199254740991;function Tn(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Pn}var jn=Tn,Is=Object.prototype,Rn="[object Arguments]";function $n(r){return vt(r)&&he(r)==Rn}var Vt=$n,or=Object.prototype,Ln=or.hasOwnProperty,Nn=or.propertyIsEnumerable,Es=Vt(function(){return arguments}())?Vt:function(r){return vt(r)&&Ln.call(r,"callee")&&!Nn.call(r,"callee")},sr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ht=sr&&typeof module=="object"&&module&&!module.nodeType&&module,On=Ht&&Ht.exports===sr,Gt=On?C.Buffer:void 0,Cs=Gt?Gt.isBuffer:void 0,Dn="[object Arguments]",Un="[object Array]",Bn="[object Boolean]",Fn="[object Date]",zn="[object Error]",qn="[object Function]",Vn="[object Map]",Hn="[object Number]",Gn="[object Object]",Wn="[object RegExp]",Qn="[object Set]",Yn="[object String]",Kn="[object WeakMap]",Jn="[object ArrayBuffer]",Xn="[object DataView]",Zn="[object Float32Array]",ei="[object Float64Array]",ti="[object Int8Array]",ri="[object Int16Array]",ni="[object Int32Array]",ii="[object Uint8Array]",oi="[object Uint8ClampedArray]",si="[object Uint16Array]",ai="[object Uint32Array]",p={};p[Zn]=p[ei]=p[ti]=p[ri]=p[ni]=p[ii]=p[oi]=p[si]=p[ai]=!0;p[Dn]=p[Un]=p[Jn]=p[Bn]=p[Xn]=p[Fn]=p[zn]=p[qn]=p[Vn]=p[Hn]=p[Gn]=p[Wn]=p[Qn]=p[Yn]=p[Kn]=!1;function li(r){return vt(r)&&jn(r.length)&&!!p[he(r)]}var ui=li;function ci(r){return function(e){return r(e)}}var di=ci,ar=typeof exports=="object"&&exports&&!exports.nodeType&&exports,de=ar&&typeof module=="object"&&module&&!module.nodeType&&module,pi=de&&de.exports===ar,gt=pi&&rr.process,fi=function(){try{var r=de&&de.require&&de.require("util").types;return r||gt&>.binding&>.binding("util")}catch{}}(),Wt=fi,Qt=Wt&&Wt.isTypedArray,Ps=Qt?di(Qt):ui,hi=Object.prototype,Ts=hi.hasOwnProperty;function gi(r,e){return function(t){return r(e(t))}}var mi=gi,js=mi(Object.keys,Object),yi=Object.prototype,Rs=yi.hasOwnProperty,bi=J(Object,"create"),pe=bi;function wi(){this.__data__=pe?pe(null):{},this.size=0}var xi=wi;function ki(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var vi=ki,_i="__lodash_hash_undefined__",Ai=Object.prototype,Si=Ai.hasOwnProperty;function Mi(r){var e=this.__data__;if(pe){var t=e[r];return t===_i?void 0:t}return Si.call(e,r)?e[r]:void 0}var Ii=Mi,Ei=Object.prototype,Ci=Ei.hasOwnProperty;function Pi(r){var e=this.__data__;return pe?e[r]!==void 0:Ci.call(e,r)}var Ti=Pi,ji="__lodash_hash_undefined__";function Ri(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=pe&&e===void 0?ji:e,this}var $i=Ri;function X(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}X.prototype.clear=xi;X.prototype.delete=vi;X.prototype.get=Ii;X.prototype.has=Ti;X.prototype.set=$i;var Yt=X;function Li(){this.__data__=[],this.size=0}var Ni=Li;function Oi(r,e){for(var t=r.length;t--;)if(Cn(r[t][0],e))return t;return-1}var Oe=Oi,Di=Array.prototype,Ui=Di.splice;function Bi(r){var e=this.__data__,t=Oe(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():Ui.call(e,t,1),--this.size,!0}var Fi=Bi;function zi(r){var e=this.__data__,t=Oe(e,r);return t<0?void 0:e[t][1]}var qi=zi;function Vi(r){return Oe(this.__data__,r)>-1}var Hi=Vi;function Gi(r,e){var t=this.__data__,n=Oe(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Wi=Gi;function Z(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}Z.prototype.clear=Ni;Z.prototype.delete=Fi;Z.prototype.get=qi;Z.prototype.has=Hi;Z.prototype.set=Wi;var De=Z,Qi=J(C,"Map"),fe=Qi;function Yi(){this.size=0,this.__data__={hash:new Yt,map:new(fe||De),string:new Yt}}var Ki=Yi;function Ji(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Xi=Ji;function Zi(r,e){var t=r.__data__;return Xi(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Ue=Zi;function eo(r){var e=Ue(this,r).delete(r);return this.size-=e?1:0,e}var to=eo;function ro(r){return Ue(this,r).get(r)}var no=ro;function io(r){return Ue(this,r).has(r)}var oo=io;function so(r,e){var t=Ue(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var ao=so;function ee(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}ee.prototype.clear=Ki;ee.prototype.delete=to;ee.prototype.get=no;ee.prototype.has=oo;ee.prototype.set=ao;var lr=ee;function lo(){this.__data__=new De,this.size=0}var uo=lo;function co(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var po=co;function fo(r){return this.__data__.get(r)}var ho=fo;function go(r){return this.__data__.has(r)}var mo=go,yo=200;function bo(r,e){var t=this.__data__;if(t instanceof De){var n=t.__data__;if(!fe||n.length<yo-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new lr(n)}return t.set(r,e),this.size=t.size,this}var wo=bo;function ge(r){var e=this.__data__=new De(r);this.size=e.size}ge.prototype.clear=uo;ge.prototype.delete=po;ge.prototype.get=ho;ge.prototype.has=mo;ge.prototype.set=wo;var xo=Object.prototype,$s=xo.propertyIsEnumerable,ko=J(C,"DataView"),bt=ko,vo=J(C,"Promise"),wt=vo,_o=J(C,"Set"),xt=_o,Kt="[object Map]",Ao="[object Object]",Jt="[object Promise]",Xt="[object Set]",Zt="[object WeakMap]",er="[object DataView]",So=U(bt),Mo=U(fe),Io=U(wt),Eo=U(xt),Co=U(yt),Y=he;(bt&&Y(new bt(new ArrayBuffer(1)))!=er||fe&&Y(new fe)!=Kt||wt&&Y(wt.resolve())!=Jt||xt&&Y(new xt)!=Xt||yt&&Y(new yt)!=Zt)&&(Y=function(r){var e=he(r),t=e==Ao?r.constructor:void 0,n=t?U(t):"";if(n)switch(n){case So:return er;case Mo:return Kt;case Io:return Jt;case Eo:return Xt;case Co:return Zt}return e});var Ls=C.Uint8Array,Po="__lodash_hash_undefined__";function To(r){return this.__data__.set(r,Po),this}var jo=To;function Ro(r){return this.__data__.has(r)}var $o=Ro;function kt(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new lr;++e<t;)this.add(r[e])}kt.prototype.add=kt.prototype.push=jo;kt.prototype.has=$o;var tr=K?K.prototype:void 0,Ns=tr?tr.valueOf:void 0,Lo=Object.prototype,Os=Lo.hasOwnProperty,No=Object.prototype,Ds=No.hasOwnProperty,Us=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Bs=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Fs=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ur(r,e){let t={...r};if(!e)return t;for(let[n,i]of Object.entries(e))i===!1||i===null||i===void 0?delete t[n]:i===!0?n in r||(t[n]=!0):t[n]=i;return t}var mt="@imgly/plugin-ai-generation",zs=`
|
|
2
2
|
<svg>
|
|
3
3
|
<symbol
|
|
4
4
|
fill="none"
|
|
@@ -59,24 +59,24 @@ var Br=typeof global=="object"&&global&&global.Object===Object&&global,rr=Br,Ur=
|
|
|
59
59
|
|
|
60
60
|
</symbol>
|
|
61
61
|
</svg>
|
|
62
|
-
`;var
|
|
62
|
+
`;var B="0.39.0";var cr=!1,F,_t,Oo,Do,Uo,dr,Bo,Be,At,pr,St,Fe,fr;function hr(r,e={auto:!1}){if(cr)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${r.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(F)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${r.kind}'\` after \`import '@anthropic-ai/sdk/shims/${F}'\``);cr=e.auto,F=r.kind,_t=r.fetch,Oo=r.Request,Do=r.Response,Uo=r.Headers,dr=r.FormData,Bo=r.Blob,Be=r.File,At=r.ReadableStream,pr=r.getMultipartRequestOptions,St=r.getDefaultAgent,Fe=r.fileFromPath,fr=r.isFsReadStream}var ze=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function gr({manuallyImported:r}={}){let e=r?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",t,n,i,o;try{t=fetch,n=Request,i=Response,o=Headers}catch(s){throw new Error(`this environment is missing the following Web Fetch API type: ${s.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:i,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(s,a)=>({...a,body:new ze(s)}),getDefaultAgent:s=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:s=>!1}}F||hr(gr(),{auto:!0});var l=class extends Error{},g=class r extends l{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.request_id=i?.["request-id"],this.error=t}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new $({message:n,cause:qe(t)});let o=t;return e===400?new me(e,o,n,i):e===401?new ye(e,o,n,i):e===403?new be(e,o,n,i):e===404?new we(e,o,n,i):e===409?new xe(e,o,n,i):e===422?new ke(e,o,n,i):e===429?new ve(e,o,n,i):e>=500?new _e(e,o,n,i):new r(e,o,n,i)}},y=class extends g{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},$=class extends g{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},te=class extends ${constructor({message:e}={}){super({message:e??"Request timed out."})}},me=class extends g{},ye=class extends g{},be=class extends g{},we=class extends g{},xe=class extends g{},ke=class extends g{},ve=class extends g{},_e=class extends g{};var Ve=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},z=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},k,P=class{constructor(){k.set(this,void 0),this.buffer=new Uint8Array,Ve(this,k,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;let i=[],o;for(;(o=qo(this.buffer,z(this,k,"f")))!=null;){if(o.carriage&&z(this,k,"f")==null){Ve(this,k,o.index,"f");continue}if(z(this,k,"f")!=null&&(o.index!==z(this,k,"f")+1||o.carriage)){i.push(this.decodeText(this.buffer.slice(0,z(this,k,"f")-1))),this.buffer=this.buffer.slice(z(this,k,"f")),Ve(this,k,null,"f");continue}let s=z(this,k,"f")!==null?o.preceding-1:o.preceding,a=this.decodeText(this.buffer.slice(0,s));i.push(a),this.buffer=this.buffer.slice(o.index),Ve(this,k,null,"f")}return i}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new l(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new l(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new l("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
63
63
|
`):[]}};k=new WeakMap;P.NEWLINE_CHARS=new Set([`
|
|
64
|
-
`,"\r"]);P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let
|
|
65
|
-
`);
|
|
66
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,i,n]=Wo(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Go=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Qo=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function yr(r,e,t){if(r=await r,Qo(r))return r;if(Go(r)){let n=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(n)?[await n.arrayBuffer()]:[n];return new Ue(o,e,t)}let i=await Yo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let n=i[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Ue(i,e,t)}async function Yo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Ko(r)}`);return e}function Ko(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var es=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},ts=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},He;async function vr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):M.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let n=await e.text();return re("response",e.status,e.url,e.headers,n),n}function _r(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ge=class r extends Promise{constructor(e,t=vr){super(i=>{i(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Qe=class{constructor({baseURL:e,maxRetries:t=2,timeout:i=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=Pt("maxRetries",t),this.timeout=Pt("timeout",i),this.httpAgent=n,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...os(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${cs()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,i){return this.request(Promise.resolve(i).then(async n=>{let o=n&&Se(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,i){return this.requestAPIList(t,{method:"get",path:e,...i})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:i,path:n,query:o,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(a),h=this.buildURL(n,o);"timeout"in e&&Pt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let x=e.httpAgent??this.httpAgent??St(h),v=e.timeout+1e3;typeof x?.options?.timeout=="number"&&v>(x.options.timeout??0)&&(x.options.timeout=v),this.idempotencyHeader&&i!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let Q=this.buildHeaders({options:e,headers:s,contentLength:f,retryCount:t});return{req:{method:i,...a&&{body:a},headers:Q,...x&&{agent:x},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:i,retryCount:n}){let o={};i&&(o["content-length"]=i);let s=this.defaultHeaders(e);return kr(o,s),kr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],We(s,"x-stainless-retry-count")===void 0&&We(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),We(s,"x-stainless-timeout")===void 0&&We(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:i}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,i,n){return g.generate(e,t,i,n)}request(e,t=null){return new Ge(this.makeRequest(e,t))}async makeRequest(e,t){let i=await e,n=i.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(i);let{req:o,url:s,timeout:a}=this.buildRequest(i,{retryCount:n-t});if(await this.prepareRequest(o,{url:s,options:i}),re("request",s,i,o.headers),i.signal?.aborted)throw new y;let f=new AbortController,h=await this.fetchWithTimeout(s,o,a,f).catch(qe);if(h instanceof Error){if(i.signal?.aborted)throw new y;if(t)return this.retryRequest(i,t);throw h.name==="AbortError"?new te:new R({cause:h})}let x=It(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,h.status,s,x),this.retryRequest(i,t,x)}let v=await h.text().catch(ft=>qe(ft).message),Q=ss(v),pt=Q?void 0:v;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,s,x,pt),this.makeStatusError(h.status,Q,pt,x)}return{response:h,options:i,controller:f}}requestAPIList(e,t){let i=this.makeRequest(t,null);return new Tt(this,i,e)}buildURL(e,t){let i=ls(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Me(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,i])=>typeof i<"u").map(([t,i])=>{if(typeof i=="string"||typeof i=="number"||typeof i=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(i)}`;if(i===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof i}; 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("&")}async fetchWithTimeout(e,t,i,n){let{signal:o,...s}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),i),f={signal:n.signal,...s};f.method&&(f.method=f.method.toUpperCase());let h=60*1e3,x=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let v of Object.values(f?.agent?.sockets).flat())v?.setKeepAlive&&v.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(a),clearTimeout(x)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,i){let n,o=i?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let s=i?.["retry-after"];if(s&&!n){let a=parseFloat(s);Number.isNaN(a)?n=Date.parse(s)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await us(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${U}`}},Ye=class{constructor(e,t,i,n){He.set(this,void 0),es(this,He,e,"f"),this.options=n,this.response=t,this.body=i}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let i=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of i)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await ts(this,He,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Tt=class extends Ge{constructor(e,t,i){super(t,async n=>new i(e,n.response,await vr(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},It=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let i=t.toString();return e[i.toLowerCase()]||e[i]}}),rs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},_=r=>typeof r=="object"&&r!==null&&!Me(r)&&Object.keys(r).every(e=>Ar(rs,e)),is=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=ns();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ns(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let i=t.exec(navigator.userAgent);if(i){let n=i[1]||0,o=i[2]||0,s=i[3]||0;return{browser:e,version:`${n}.${o}.${s}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),xr,os=()=>xr??(xr=is()),ss=r=>{try{return JSON.parse(r)}catch{return}},as=/^[a-z][a-z0-9+.-]*:/i,ls=r=>as.test(r),us=r=>new Promise(e=>setTimeout(e,r)),Pt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var Ke=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Me(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function kr(r,e){for(let t in e){if(!Ar(e,t))continue;let i=t.toLowerCase();if(!i)continue;let n=e[t];n===null?delete r[i]:n!==void 0&&(r[i]=n)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var cs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ds=r=>typeof r?.get=="function";var We=(r,e)=>{let t=e.toLowerCase();if(ds(r)){let i=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,s)=>o+s.toUpperCase());for(let n of[e,t,e.toUpperCase(),i]){let o=r.get(n);if(o)return o}}for(let[i,n]of Object.entries(r))if(i.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var I=class extends Ye{constructor(e,t,i,n){super(e,t,i,n),this.data=i.data||[],this.has_more=i.has_more||!1,this.first_id=i.first_id||null,this.last_id=i.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ie,{query:e,...t})}},ie=class extends I{};q.BetaModelInfosPage=ie;var ne=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new P;for await(let t of this.iterator)for(let i of e.decode(t))yield JSON.parse(i);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},i){if(_(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:i,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:n,...t,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},i){if(_(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}cancel(e,t={},i){if(_(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...i,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...i?.headers}})}async results(e,t={},i){if(_(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:o}=t;return this._client.get(n.results_url,{...i,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...i?.headers},__binaryResponse:!0})._thenUnwrap((s,a)=>ne.fromResponse(a.response,a.controller))}},oe=class extends I{};V.BetaMessageBatchesPage=oe;var gs=r=>{let e=0,t=[];for(;e<r.length;){let i=r[e];if(i==="\\"){e++;continue}if(i==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(i==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(i==="["){t.push({type:"paren",value:"["}),e++;continue}if(i==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(i===":"){t.push({type:"separator",value:":"}),e++;continue}if(i===","){t.push({type:"delimiter",value:","}),e++;continue}if(i==='"'){let a="",f=!1;for(i=r[++e];i!=='"';){if(e===r.length){f=!0;break}if(i==="\\"){if(e++,e===r.length){f=!0;break}a+=i+r[e],i=r[++e]}else a+=i,i=r[++e]}i=r[++e],f||t.push({type:"string",value:a});continue}if(i&&/\s/.test(i)){e++;continue}let o=/[0-9]/;if(i&&o.test(i)||i==="-"||i==="."){let a="";for(i==="-"&&(a+=i,i=r[++e]);i&&o.test(i)||i===".";)a+=i,i=r[++e];t.push({type:"number",value:a});continue}let s=/[a-z]/i;if(i&&s.test(i)){let a="";for(;i&&s.test(i)&&e!==r.length;)a+=i,i=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},se=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),se(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),se(r);case"string":let i=r[r.length-2];if(i?.type==="delimiter")return r=r.slice(0,r.length-1),se(r);if(i?.type==="brace"&&i.value==="{")return r=r.slice(0,r.length-1),se(r);break;case"delimiter":return r=r.slice(0,r.length-1),se(r);break}return r},ms=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},ys=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ys(ms(se(gs(r)))));var b=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},u=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},A,L,Ie,Xe,Ee,Ce,Ze,Pe,T,Te,et,tt,ae,rt,it,$t,Mr,jt,Rt,Lt,Nt,Ir,Er="__json_buf",nt=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Ie.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Pe.set(this,()=>{}),T.set(this,{}),Te.set(this,!1),et.set(this,!1),tt.set(this,!1),ae.set(this,!1),rt.set(this,void 0),it.set(this,void 0),jt.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Ie,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Pe,t,"f")}),"f"),u(this,Ie,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,it,"f")}async withResponse(){let e=await u(this,Ie,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,jt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)u(this,A,"m",Lt).call(this,a);if(s.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,it,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Te,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=u(this,T,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{b(this,ae,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){b(this,ae,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",$t).call(this)}async finalText(){return await this.done(),u(this,A,"m",Mr).call(this)}_emit(e,...t){if(u(this,Te,"f"))return;e==="end"&&(b(this,Te,!0,"f"),u(this,Ze,"f").call(this));let i=u(this,T,"f")[e];if(i&&(u(this,T,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,ae,"f")&&!i?.length&&Promise.reject(n),u(this,Ee,"f").call(this,n),u(this,Pe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",$t).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",Rt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)u(this,A,"m",Lt).call(this,o);if(n.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}[(L=new WeakMap,Ie=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Pe=new WeakMap,T=new WeakMap,Te=new WeakMap,et=new WeakMap,tt=new WeakMap,ae=new WeakMap,rt=new WeakMap,it=new WeakMap,jt=new WeakMap,A=new WeakSet,$t=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Mr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Rt=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let i=u(this,A,"m",Ir).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{b(this,L,i,"f");break}case"content_block_start":case"message_delta":break}},Nt=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Ir=function(t){let i=u(this,L,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[Er]||"";o+=t.delta.partial_json,Object.defineProperty(n,Er,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},N=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:i,...n}=e;return n.model in Cr&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Cr[n.model]}
|
|
67
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:n,timeout:this._client._options.timeout??(n.stream?6e5:this._client._calculateNonstreamingTimeout(n.max_tokens)),...t,headers:{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return nt.createMessage(this,e,t)}countTokens(e,t){let{betas:i,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...i??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};N.Batches=V;N.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new N(this._client)}};E.Models=q;E.BetaModelInfosPage=ie;E.Messages=N;var H=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var W=class extends m{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);return this._client.get(i.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,o)=>ne.fromResponse(o.response,o.controller))}},le=class extends I{};W.MessageBatchesPage=le;var w=function(r,e,t,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t},c=function(r,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(r):i?i.value:e.get(r)},S,O,$e,ot,je,Re,st,Le,$,Ne,at,lt,ue,ut,ct,Ot,Pr,Dt,Bt,Ut,Ft,Tr,$r="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],O.set(this,void 0),this.controller=new AbortController,$e.set(this,void 0),ot.set(this,()=>{}),je.set(this,()=>{}),Re.set(this,void 0),st.set(this,()=>{}),Le.set(this,()=>{}),$.set(this,{}),Ne.set(this,!1),at.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,$e,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,je,t,"f")}),"f"),w(this,Re,new Promise((e,t)=>{w(this,st,e,"f"),w(this,Le,t,"f")}),"f"),c(this,$e,"f").catch(()=>{}),c(this,Re,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(this,$e,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,i){let n=new r;for(let o of t.messages)n._addMessageParam(o);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,i){let n=i?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...i,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)c(this,S,"m",Ut).call(this,a);if(s.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Ne,"f")}get errored(){return c(this,at,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t}),this}off(e,t){let i=c(this,$,"f")[e];if(!i)return this;let n=i.findIndex(o=>o.listener===t);return n>=0&&i.splice(n,1),this}once(e,t){return(c(this,$,"f")[e]||(c(this,$,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,i)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",i),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,Re,"f")}get currentMessage(){return c(this,O,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Ot).call(this)}async finalText(){return await this.done(),c(this,S,"m",Pr).call(this)}_emit(e,...t){if(c(this,Ne,"f"))return;e==="end"&&(w(this,Ne,!0,"f"),c(this,st,"f").call(this));let i=c(this,$,"f")[e];if(i&&(c(this,$,"f")[e]=i.filter(n=>!n.once),i.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,je,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,ue,"f")&&!i?.length&&Promise.reject(n),c(this,je,"f").call(this,n),c(this,Le,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Ot).call(this))}async _fromReadableStream(e,t){let i=t?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Bt).call(this),this._connected(null);let n=M.fromReadableStream(e,this.controller);for await(let o of n)c(this,S,"m",Ut).call(this,o);if(n.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(O=new WeakMap,$e=new WeakMap,ot=new WeakMap,je=new WeakMap,Re=new WeakMap,st=new WeakMap,Le=new WeakMap,$=new WeakMap,Ne=new WeakMap,at=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Ot=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Pr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(i=>i.type==="text").map(i=>i.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Bt=function(){this.ended||w(this,O,void 0,"f")},Ut=function(t){if(this.ended)return;let i=c(this,S,"m",Tr).call(this,t);switch(this._emit("streamEvent",t,i),t.type){case"content_block_delta":{let n=i.content.at(-1);switch(t.delta.type){case"text_delta":{n.type==="text"&&this._emit("text",t.delta.text,n.text||"");break}case"citations_delta":{n.type==="text"&&this._emit("citation",t.delta.citation,n.citations??[]);break}case"input_json_delta":{n.type==="tool_use"&&n.input&&this._emit("inputJson",t.delta.partial_json,n.input);break}case"thinking_delta":{n.type==="thinking"&&this._emit("thinking",t.delta.thinking,n.thinking);break}case"signature_delta":{n.type==="thinking"&&this._emit("signature",n.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(i),this._addMessage(i,!0);break}case"content_block_stop":{this._emit("contentBlock",i.content.at(-1));break}case"message_start":{w(this,O,i,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,O,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,O,void 0,"f"),t},Tr=function(t){let i=c(this,O,"f");if(t.type==="message_start"){if(i)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!i)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return i;case"message_delta":return i.stop_reason=t.delta.stop_reason,i.stop_sequence=t.delta.stop_sequence,i.usage.output_tokens=t.usage.output_tokens,i;case"content_block_start":return i.content.push(t.content_block),i;case"content_block_delta":{let n=i.content.at(t.index);switch(t.delta.type){case"text_delta":{n?.type==="text"&&(n.text+=t.delta.text);break}case"citations_delta":{n?.type==="text"&&(n.citations??(n.citations=[]),n.citations.push(t.delta.citation));break}case"input_json_delta":{if(n?.type==="tool_use"){let o=n[$r]||"";o+=t.delta.partial_json,Object.defineProperty(n,$r,{value:o,enumerable:!1,writable:!0}),o&&(n.input=Je(o))}break}case"thinking_delta":{n?.type==="thinking"&&(n.thinking+=t.delta.thinking);break}case"signature_delta":{n?.type==="thinking"&&(n.signature=t.delta.signature);break}default:t.delta}return i}case"content_block_stop":return i}},Symbol.asyncIterator)](){let e=[],t=[],i=!1;return this.on("streamEvent",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{i=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{i=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:i?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var j=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in jr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${jr[e.model]}
|
|
68
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},
|
|
64
|
+
`,"\r"]);P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let i=e??0;i<r.length;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function mr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function Ae(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var M=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let s of Vo(e,t)){if(s.event==="completion")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event==="message_start"||s.event==="message_delta"||s.event==="message_stop"||s.event==="content_block_start"||s.event==="content_block_delta"||s.event==="content_block_stop")try{yield JSON.parse(s.data)}catch(a){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),a}if(s.event!=="ping"&&s.event==="error")throw g.generate(void 0,`SSE Error: ${s.data}`,s.data,It(e.headers))}o=!0}catch(s){if(s instanceof Error&&s.name==="AbortError")return;throw s}finally{o||t.abort()}}return new r(i,t)}static fromReadableStream(e,t){let n=!1;async function*i(){let s=new P,a=Ae(e);for await(let f of a)for(let h of s.decode(f))yield h;for(let f of s.flush())yield f}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(let a of i())s||a&&(yield JSON.parse(a));s=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{s||t.abort()}}return new r(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=o=>({next:()=>{if(o.length===0){let s=n.next();e.push(s),t.push(s)}return o.shift()}});return[new r(()=>i(e),this.controller),new r(()=>i(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new At({async start(){t=e[Symbol.asyncIterator]()},async pull(i){try{let{value:o,done:s}=await t.next();if(s)return i.close();let a=n.encode(JSON.stringify(o)+`
|
|
65
|
+
`);i.enqueue(a)}catch(o){i.error(o)}},async cancel(){await t.return?.()}})}};async function*Vo(r,e){if(!r.body)throw e.abort(),new l("Attempted to iterate over a response with no body");let t=new Mt,n=new P,i=Ae(r.body);for await(let o of Ho(i))for(let s of n.decode(o)){let a=t.decode(s);a&&(yield a)}for(let o of n.flush()){let s=t.decode(o);s&&(yield s)}}async function*Ho(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let o;for(;(o=mr(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Mt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
66
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,i]=Go(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Go(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Wo=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Qo=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Se(r),Se=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function";async function yr(r,e,t){if(r=await r,Qo(r))return r;if(Wo(r)){let i=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Se(i)?[await i.arrayBuffer()]:[i];return new Be(o,e,t)}let n=await Yo(r);if(e||(e=Jo(r)??"unknown_file"),!t?.type){let i=n[0]?.type;typeof i=="string"&&(t={...t,type:i})}return new Be(n,e,t)}async function Yo(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Se(r))e.push(await r.arrayBuffer());else if(Xo(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${Ko(r)}`);return e}function Ko(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Jo(r){return Et(r.name)||Et(r.filename)||Et(r.path)?.split(/[\\/]/).pop()}var Et=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Xo=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ct=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var es=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},ts=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},He;async function vr(r){let{response:e}=r;if(r.options.stream)return re("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):M.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let o=await e.json();return re("response",e.status,e.url,e.headers,o),_r(o,e)}let i=await e.text();return re("response",e.status,e.url,e.headers,i),i}function _r(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var We=class r extends Promise{constructor(e,t=vr){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>_r(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},Qe=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:i,fetch:o}){this.baseURL=e,this.maxRetries=Pt("maxRetries",t),this.timeout=Pt("timeout",n),this.httpAgent=i,this.fetch=o??_t}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...os(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${cs()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async i=>{let o=i&&Se(i?.body)?new DataView(await i.body.arrayBuffer()):i?.body instanceof DataView?i.body:i?.body instanceof ArrayBuffer?new DataView(i.body):i&&ArrayBuffer.isView(i?.body)?new DataView(i.body.buffer):i?.body;return{method:e,path:t,...i,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};let{method:n,path:i,query:o,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Ct(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,f=this.calculateContentLength(a),h=this.buildURL(i,o);"timeout"in e&&Pt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let x=e.httpAgent??this.httpAgent??St(h),v=e.timeout+1e3;typeof x?.options?.timeout=="number"&&v>(x.options.timeout??0)&&(x.options.timeout=v),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let Q=this.buildHeaders({options:e,headers:s,contentLength:f,retryCount:t});return{req:{method:n,...a&&{body:a},headers:Q,...x&&{agent:x},signal:e.signal??null},url:h,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:i}){let o={};n&&(o["content-length"]=n);let s=this.defaultHeaders(e);return kr(o,s),kr(o,t),Ct(e.body)&&F!=="node"&&delete o["content-type"],Ge(s,"x-stainless-retry-count")===void 0&&Ge(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(i)),Ge(s,"x-stainless-timeout")===void 0&&Ge(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(o,t),o}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new l("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,i){return g.generate(e,t,n,i)}request(e,t=null){return new We(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,i=n.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(n);let{req:o,url:s,timeout:a}=this.buildRequest(n,{retryCount:i-t});if(await this.prepareRequest(o,{url:s,options:n}),re("request",s,n,o.headers),n.signal?.aborted)throw new y;let f=new AbortController,h=await this.fetchWithTimeout(s,o,a,f).catch(qe);if(h instanceof Error){if(n.signal?.aborted)throw new y;if(t)return this.retryRequest(n,t);throw h.name==="AbortError"?new te:new $({cause:h})}let x=It(h.headers);if(!h.ok){if(t&&this.shouldRetry(h)){let ft=`retrying, ${t} attempts remaining`;return re(`response (error; ${ft})`,h.status,s,x),this.retryRequest(n,t,x)}let v=await h.text().catch(ft=>qe(ft).message),Q=ss(v),pt=Q?void 0:v;throw re(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,h.status,s,x,pt),this.makeStatusError(h.status,Q,pt,x)}return{response:h,options:n,controller:f}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new Tt(this,n,e)}buildURL(e,t){let n=ls(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Me(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new l(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,i){let{signal:o,...s}=t||{};o&&o.addEventListener("abort",()=>i.abort());let a=setTimeout(()=>i.abort(),n),f={signal:i.signal,...s};f.method&&(f.method=f.method.toUpperCase());let h=60*1e3,x=setTimeout(()=>{if(f&&f?.agent?.sockets)for(let v of Object.values(f?.agent?.sockets).flat())v?.setKeepAlive&&v.setKeepAlive(!0,h)},h);return this.fetch.call(void 0,e,f).finally(()=>{clearTimeout(a),clearTimeout(x)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let i,o=n?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(i=a)}let s=n?.["retry-after"];if(s&&!i){let a=parseFloat(s);Number.isNaN(a)?i=Date.parse(s)-Date.now():i=a*1e3}if(!(i&&0<=i&&i<60*1e3)){let a=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,a)}return await us(i),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,s=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${B}`}},Ye=class{constructor(e,t,n,i){He.set(this,void 0),es(this,He,e,"f"),this.options=i,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[i,o]of n)e.url.searchParams.set(i,o);t.query=void 0,t.path=e.url.toString()}return await ts(this,He,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(He=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Tt=class extends We{constructor(e,t,n){super(t,async i=>new n(e,i.response,await vr(i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},It=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),rs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},_=r=>typeof r=="object"&&r!==null&&!Me(r)&&Object.keys(r).every(e=>Ar(rs,e)),ns=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":wr(Deno.build.os),"X-Stainless-Arch":br(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":wr(process.platform),"X-Stainless-Arch":br(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=is();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function is(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,o=n[2]||0,s=n[3]||0;return{browser:e,version:`${i}.${o}.${s}`}}}return null}var br=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",wr=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),xr,os=()=>xr??(xr=ns()),ss=r=>{try{return JSON.parse(r)}catch{return}},as=/^[a-z][a-z0-9+.-]*:/i,ls=r=>as.test(r),us=r=>new Promise(e=>setTimeout(e,r)),Pt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new l(`${r} must be an integer`);if(e<0)throw new l(`${r} must be a positive integer`);return e},qe=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(String(r))};var Ke=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Me(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ar(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function kr(r,e){for(let t in e){if(!Ar(e,t))continue;let n=t.toLowerCase();if(!n)continue;let i=e[t];i===null?delete r[n]:i!==void 0&&(r[n]=i)}}function re(r,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${r}`,...e)}var cs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Sr=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ds=r=>typeof r?.get=="function";var Ge=(r,e)=>{let t=e.toLowerCase();if(ds(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(i,o,s)=>o+s.toUpperCase());for(let i of[e,t,e.toUpperCase(),n]){let o=r.get(i);if(o)return o}}for(let[n,i]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(i)?(i.length<=1||console.warn(`Received ${i.length} entries for the ${e} header, using the first entry.`),i[0]):i};var I=class extends Ye{constructor(e,t,n,i){super(e,t,n,i),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(this.options.query?.before_id){let t=this.first_id;return t?{params:{before_id:t}}:null}let e=this.last_id;return e?{params:{after_id:e}}:null}};var m=class{constructor(e){this._client=e}};var q=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",ne,{query:e,...t})}},ne=class extends I{};q.BetaModelInfosPage=ne;var ie=class r{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new P;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),new l("Attempted to iterate over a response with no body");return new r(Ae(e.body),t)}};var V=class extends m{create(e,t){let{betas:n,...i}=e;return this._client.post("/v1/messages/batches?beta=true",{body:i,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},n){if(_(t))return this.retrieve(e,{},t);let{betas:i}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}list(e={},t){if(_(e))return this.list({},e);let{betas:n,...i}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",oe,{query:i,...t,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},n){if(_(t))return this.delete(e,{},t);let{betas:i}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}cancel(e,t={},n){if(_(t))return this.cancel(e,{},t);let{betas:i}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),...n?.headers}})}async results(e,t={},n){if(_(t))return this.results(e,{},t);let i=await this.retrieve(e);if(!i.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${i.processing_status} - ${i.id}`);let{betas:o}=t;return this._client.get(i.results_url,{...n,headers:{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...n?.headers},__binaryResponse:!0})._thenUnwrap((s,a)=>ie.fromResponse(a.response,a.controller))}},oe=class extends I{};V.BetaMessageBatchesPage=oe;var gs=r=>{let e=0,t=[];for(;e<r.length;){let n=r[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",f=!1;for(n=r[++e];n!=='"';){if(e===r.length){f=!0;break}if(n==="\\"){if(e++,e===r.length){f=!0;break}a+=n+r[e],n=r[++e]}else a+=n,n=r[++e]}n=r[++e],f||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=r[++e]);n&&o.test(n)||n===".";)a+=n,n=r[++e];t.push({type:"number",value:a});continue}let s=/[a-z]/i;if(n&&s.test(n)){let a="";for(;n&&s.test(n)&&e!==r.length;)a+=n,n=r[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},se=r=>{if(r.length===0)return r;let e=r[r.length-1];switch(e.type){case"separator":return r=r.slice(0,r.length-1),se(r);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return r=r.slice(0,r.length-1),se(r);case"string":let n=r[r.length-2];if(n?.type==="delimiter")return r=r.slice(0,r.length-1),se(r);if(n?.type==="brace"&&n.value==="{")return r=r.slice(0,r.length-1),se(r);break;case"delimiter":return r=r.slice(0,r.length-1),se(r);break}return r},ms=r=>{let e=[];return r.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?r.push({type:"brace",value:"}"}):t==="]"&&r.push({type:"paren",value:"]"})}),r},ys=r=>{let e="";return r.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Je=r=>JSON.parse(ys(ms(se(gs(r)))));var b=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},u=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},A,L,Ie,Xe,Ee,Ce,Ze,Pe,T,Te,et,tt,ae,rt,nt,jt,Mr,Rt,$t,Lt,Nt,Ir,Er="__json_buf",it=class r{constructor(){A.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),this.controller=new AbortController,Ie.set(this,void 0),Xe.set(this,()=>{}),Ee.set(this,()=>{}),Ce.set(this,void 0),Ze.set(this,()=>{}),Pe.set(this,()=>{}),T.set(this,{}),Te.set(this,!1),et.set(this,!1),tt.set(this,!1),ae.set(this,!1),rt.set(this,void 0),nt.set(this,void 0),Rt.set(this,e=>{if(b(this,et,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return b(this,tt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),b(this,Ie,new Promise((e,t)=>{b(this,Xe,e,"f"),b(this,Ee,t,"f")}),"f"),b(this,Ce,new Promise((e,t)=>{b(this,Ze,e,"f"),b(this,Pe,t,"f")}),"f"),u(this,Ie,"f").catch(()=>{}),u(this,Ce,"f").catch(()=>{})}get response(){return u(this,rt,"f")}get request_id(){return u(this,nt,"f")}async withResponse(){let e=await u(this,Ie,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let i=new r;for(let o of t.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,Rt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",$t).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)u(this,A,"m",Lt).call(this,a);if(s.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}_connected(e){this.ended||(b(this,rt,e,"f"),b(this,nt,e?.headers.get("request-id"),"f"),u(this,Xe,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,Te,"f")}get errored(){return u(this,et,"f")}get aborted(){return u(this,tt,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=u(this,T,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(u(this,T,"f")[e]||(u(this,T,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,ae,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){b(this,ae,!0,"f"),await u(this,Ce,"f")}get currentMessage(){return u(this,L,"f")}async finalMessage(){return await this.done(),u(this,A,"m",jt).call(this)}async finalText(){return await this.done(),u(this,A,"m",Mr).call(this)}_emit(e,...t){if(u(this,Te,"f"))return;e==="end"&&(b(this,Te,!0,"f"),u(this,Ze,"f").call(this));let n=u(this,T,"f")[e];if(n&&(u(this,T,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!u(this,ae,"f")&&!n?.length&&Promise.reject(i),u(this,Ee,"f").call(this,i),u(this,Pe,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!u(this,ae,"f")&&!n?.length&&Promise.reject(i),u(this,Ee,"f").call(this,i),u(this,Pe,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,A,"m",jt).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,A,"m",$t).call(this),this._connected(null);let i=M.fromReadableStream(e,this.controller);for await(let o of i)u(this,A,"m",Lt).call(this,o);if(i.controller.signal?.aborted)throw new y;u(this,A,"m",Nt).call(this)}[(L=new WeakMap,Ie=new WeakMap,Xe=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Pe=new WeakMap,T=new WeakMap,Te=new WeakMap,et=new WeakMap,tt=new WeakMap,ae=new WeakMap,rt=new WeakMap,nt=new WeakMap,Rt=new WeakMap,A=new WeakSet,jt=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Mr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},$t=function(){this.ended||b(this,L,void 0,"f")},Lt=function(t){if(this.ended)return;let n=u(this,A,"m",Ir).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{i.type==="tool_use"&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{b(this,L,n,"f");break}case"content_block_start":case"message_delta":break}},Nt=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=u(this,L,"f");if(!t)throw new l("request ended without sending any chunks");return b(this,L,void 0,"f"),t},Ir=function(t){let n=u(this,L,"f");if(t.type==="message_start"){if(n)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(i.text+=t.delta.text);break}case"citations_delta":{i?.type==="text"&&(i.citations??(i.citations=[]),i.citations.push(t.delta.citation));break}case"input_json_delta":{if(i?.type==="tool_use"){let o=i[Er]||"";o+=t.delta.partial_json,Object.defineProperty(i,Er,{value:o,enumerable:!1,writable:!0}),o&&(i.input=Je(o))}break}case"thinking_delta":{i?.type==="thinking"&&(i.thinking+=t.delta.thinking);break}case"signature_delta":{i?.type==="thinking"&&(i.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Cr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},N=class extends m{constructor(){super(...arguments),this.batches=new V(this._client)}create(e,t){let{betas:n,...i}=e;return i.model in Cr&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Cr[i.model]}
|
|
67
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:i,timeout:this._client._options.timeout??(i.stream?6e5:this._client._calculateNonstreamingTimeout(i.max_tokens)),...t,headers:{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return it.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...i}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};N.Batches=V;N.BetaMessageBatchesPage=oe;var E=class extends m{constructor(){super(...arguments),this.models=new q(this._client),this.messages=new N(this._client)}};E.Models=q;E.BetaModelInfosPage=ne;E.Messages=N;var H=class extends m{create(e,t){return this._client.post("/v1/complete",{body:e,timeout:this._client._options.timeout??6e5,...t,stream:e.stream??!1})}};var G=class extends m{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/v1/messages/batches/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",le,{query:e,...t})}delete(e,t){return this._client.delete(`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new l(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((i,o)=>ie.fromResponse(o.response,o.controller))}},le=class extends I{};G.MessageBatchesPage=le;var w=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},c=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},S,O,je,ot,Re,$e,st,Le,j,Ne,at,lt,ue,ut,ct,Ot,Pr,Dt,Ut,Bt,Ft,Tr,jr="__json_buf",dt=class r{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],O.set(this,void 0),this.controller=new AbortController,je.set(this,void 0),ot.set(this,()=>{}),Re.set(this,()=>{}),$e.set(this,void 0),st.set(this,()=>{}),Le.set(this,()=>{}),j.set(this,{}),Ne.set(this,!1),at.set(this,!1),lt.set(this,!1),ue.set(this,!1),ut.set(this,void 0),ct.set(this,void 0),Dt.set(this,e=>{if(w(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new y),e instanceof y)return w(this,lt,!0,"f"),this._emit("abort",e);if(e instanceof l)return this._emit("error",e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new l(String(e)))}),w(this,je,new Promise((e,t)=>{w(this,ot,e,"f"),w(this,Re,t,"f")}),"f"),w(this,$e,new Promise((e,t)=>{w(this,st,e,"f"),w(this,Le,t,"f")}),"f"),c(this,je,"f").catch(()=>{}),c(this,$e,"f").catch(()=>{})}get response(){return c(this,ut,"f")}get request_id(){return c(this,ct,"f")}async withResponse(){let e=await c(this,je,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){let i=new r;for(let o of t.messages)i._addMessageParam(o);return i._run(()=>i._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Dt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this);let{response:o,data:s}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(let a of s)c(this,S,"m",Bt).call(this,a);if(s.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}_connected(e){this.ended||(w(this,ut,e,"f"),w(this,ct,e?.headers.get("request-id"),"f"),c(this,ot,"f").call(this,e),this._emit("connect"))}get ended(){return c(this,Ne,"f")}get errored(){return c(this,at,"f")}get aborted(){return c(this,lt,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=c(this,j,"f")[e];if(!n)return this;let i=n.findIndex(o=>o.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(c(this,j,"f")[e]||(c(this,j,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,ue,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,ue,!0,"f"),await c(this,$e,"f")}get currentMessage(){return c(this,O,"f")}async finalMessage(){return await this.done(),c(this,S,"m",Ot).call(this)}async finalText(){return await this.done(),c(this,S,"m",Pr).call(this)}_emit(e,...t){if(c(this,Ne,"f"))return;e==="end"&&(w(this,Ne,!0,"f"),c(this,st,"f").call(this));let n=c(this,j,"f")[e];if(n&&(c(this,j,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!c(this,ue,"f")&&!n?.length&&Promise.reject(i),c(this,Re,"f").call(this,i),c(this,Le,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!c(this,ue,"f")&&!n?.length&&Promise.reject(i),c(this,Re,"f").call(this,i),c(this,Le,"f").call(this,i),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",c(this,S,"m",Ot).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),c(this,S,"m",Ut).call(this),this._connected(null);let i=M.fromReadableStream(e,this.controller);for await(let o of i)c(this,S,"m",Bt).call(this,o);if(i.controller.signal?.aborted)throw new y;c(this,S,"m",Ft).call(this)}[(O=new WeakMap,je=new WeakMap,ot=new WeakMap,Re=new WeakMap,$e=new WeakMap,st=new WeakMap,Le=new WeakMap,j=new WeakMap,Ne=new WeakMap,at=new WeakMap,lt=new WeakMap,ue=new WeakMap,ut=new WeakMap,ct=new WeakMap,Dt=new WeakMap,S=new WeakSet,Ot=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Pr=function(){if(this.receivedMessages.length===0)throw new l("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new l("stream ended without producing a content block with type=text");return t.join(" ")},Ut=function(){this.ended||w(this,O,void 0,"f")},Bt=function(t){if(this.ended)return;let n=c(this,S,"m",Tr).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{let i=n.content.at(-1);switch(t.delta.type){case"text_delta":{i.type==="text"&&this._emit("text",t.delta.text,i.text||"");break}case"citations_delta":{i.type==="text"&&this._emit("citation",t.delta.citation,i.citations??[]);break}case"input_json_delta":{i.type==="tool_use"&&i.input&&this._emit("inputJson",t.delta.partial_json,i.input);break}case"thinking_delta":{i.type==="thinking"&&this._emit("thinking",t.delta.thinking,i.thinking);break}case"signature_delta":{i.type==="thinking"&&this._emit("signature",i.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{w(this,O,n,"f");break}case"content_block_start":case"message_delta":break}},Ft=function(){if(this.ended)throw new l("stream has ended, this shouldn't happen");let t=c(this,O,"f");if(!t)throw new l("request ended without sending any chunks");return w(this,O,void 0,"f"),t},Tr=function(t){let n=c(this,O,"f");if(t.type==="message_start"){if(n)throw new l(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new l(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{let i=n.content.at(t.index);switch(t.delta.type){case"text_delta":{i?.type==="text"&&(i.text+=t.delta.text);break}case"citations_delta":{i?.type==="text"&&(i.citations??(i.citations=[]),i.citations.push(t.delta.citation));break}case"input_json_delta":{if(i?.type==="tool_use"){let o=i[jr]||"";o+=t.delta.partial_json,Object.defineProperty(i,jr,{value:o,enumerable:!1,writable:!0}),o&&(i.input=Je(o))}break}case"thinking_delta":{i?.type==="thinking"&&(i.thinking+=t.delta.thinking);break}case"signature_delta":{i?.type==="thinking"&&(i.signature=t.delta.signature);break}default:t.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("streamEvent",i=>{let o=t.shift();o?o.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let o of t)o.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,s)=>t.push({resolve:o,reject:s})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new M(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var R=class extends m{constructor(){super(...arguments),this.batches=new G(this._client)}create(e,t){return e.model in Rr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Rr[e.model]}
|
|
68
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:e,timeout:this._client._options.timeout??(e.stream?6e5:this._client._calculateNonstreamingTimeout(e.max_tokens)),...t,stream:e.stream??!1})}stream(e,t){return dt.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Rr={"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-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};R.Batches=G;R.MessageBatchesPage=le;var D=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return _(e)?this.list({},e):this._client.getAPIList("/v1/models",W,{query:e,...t})}},W=class extends I{};D.ModelInfosPage=W;var $r,d=class extends Qe{constructor({baseURL:e=Ke("ANTHROPIC_BASE_URL"),apiKey:t=Ke("ANTHROPIC_API_KEY")??null,authToken:n=Ke("ANTHROPIC_AUTH_TOKEN")??null,...i}={}){let o={apiKey:t,authToken:n,...i,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&Sr())throw new l(`It looks like you're running in a browser-like environment.
|
|
69
69
|
|
|
70
70
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
71
71
|
If you understand the risks and have appropriate mitigations in place,
|
|
72
72
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
73
73
|
|
|
74
74
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
75
|
-
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new H(this),this.messages=new
|
|
75
|
+
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new H(this),this.messages=new R(this),this.models=new D(this),this.beta=new E(this),this._options=o,this.apiKey=t,this.authToken=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(e,t){if(!(this.apiKey&&e["x-api-key"])&&t["x-api-key"]!==null&&!(this.authToken&&e.authorization)&&t.authorization!==null)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')}authHeaders(e){let t=this.apiKeyAuth(e),n=this.bearerAuth(e);return t!=null&&!Me(t)?t:n!=null&&!Me(n)?n:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};$r=d;d.Anthropic=$r;d.HUMAN_PROMPT=`
|
|
76
76
|
|
|
77
77
|
Human:`;d.AI_PROMPT=`
|
|
78
78
|
|
|
79
|
-
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=g;d.APIConnectionError
|
|
79
|
+
Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=g;d.APIConnectionError=$;d.APIConnectionTimeoutError=te;d.APIUserAbortError=y;d.NotFoundError=we;d.ConflictError=xe;d.RateLimitError=ve;d.BadRequestError=me;d.AuthenticationError=ye;d.InternalServerError=_e;d.PermissionDeniedError=be;d.UnprocessableEntityError=ke;d.toFile=yr;d.fileFromPath=Fe;d.Completions=H;d.Messages=R;d.Models=D;d.ModelInfosPage=W;d.Beta=E;var{HUMAN_PROMPT:xl,AI_PROMPT:kl}=d,Lr=d;var ks={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Nr={headers:{"x-api-key":null,authorization:null}};async function vs(r,e,t,n){let i={};e.model&&(i.model=e.model),e.maxTokens&&(i.max_tokens=e.maxTokens),e.temperature&&(i.temperature=e.temperature);let o=await r.messages.create({...ks,...i,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:n,...Nr,headers:{...Nr.headers??{},...e.headers}});async function*s(){try{for await(let a of o)a.type==="content_block_delta"&&a.delta.type==="text_delta"&&(yield a.delta.text)}catch(a){throw console.error("Stream error:",a),a}}return s()}var Or=vs;function Dr(r){return()=>{let e=null,n=ur({"ly.img.improve":!0,"ly.img.fix":{},"ly.img.shorter":!0,"ly.img.longer":{},"ly.img.changeTone":!0,"ly.img.translate":!0,"ly.img.changeTextTo":{}},r.supportedQuickActions),i={kind:"text",id:"anthropic",name:"Anthropic",initialize:async()=>{e=new Lr({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{supported:n}},output:{middleware:r.middlewares??r.middleware??[],generate:async({prompt:o,blockId:s},{engine:a,abortSignal:f})=>{if(e==null)throw new Error("Anthropic SDK is not initialized");if(s!=null&&a.block.getType(s)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it most be a text block");r.debug&&console.log("Sending prompt to Anthropic:",JSON.stringify(o,void 0,2));let h=await Or(e,{proxyUrl:r.proxyUrl,headers:r.headers,model:r.model??"claude-3-7-sonnet-20250219"},o,f);async function*x(){let v="";for await(let Q of h){if(f?.aborted)break;v+=Q,yield{kind:"text",text:v}}return{kind:"text",text:v}}return x()}}};return Promise.resolve(i)}}var _s={AnthropicProvider:Dr},Cl=_s;export{Cl as default};
|
|
80
80
|
/*! Bundled license information:
|
|
81
81
|
|
|
82
82
|
@imgly/plugin-ai-generation-web/dist/index.mjs:
|