@imgly/plugin-ai-text-generation-web 0.2.3 → 0.2.4

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 CHANGED
@@ -2,11 +2,23 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.2.4] - 2025-08-07
6
+
7
+ ### New Features
8
+
9
+ - [all] **Provider Label Translations**: Added support for provider label translations
10
+ - [all] **Extended Provider Configuration**: Added support for `history` and `supportedQuickActions` configuration fields in `CommonProviderConfiguration`, allowing customers to:
11
+ - Override provider's default history asset source (`history` field) - can be set to `false` to disable history, `'@imgly/local'` for temporary storage, `'@imgly/indexedDB'` for persistent browser storage, or any custom asset source ID
12
+ - Configure supported quick actions (`supportedQuickActions` field) - can disable quick actions by setting to `false`/`null`, keep defaults with `true`, or override with custom mappings and configurations
13
+ - Both fields are optional and maintain backward compatibility with existing provider configurations
14
+ - [generation-web] **Utility Function**: Added `mergeQuickActionsConfig` utility function for merging provider defaults with user configuration overrides, exported from `@imgly/plugin-ai-generation-web` with comprehensive Jest test coverage
15
+
5
16
  ## [0.2.3] - 2025-07-23
6
17
 
7
18
  - [all] **Automatic History Asset Library Entries**: Composite history asset sources now automatically have corresponding asset library entries created with the same IDs (e.g., `ly.img.ai.image-generation.history`)
8
19
  - [all] **Provider Selection in Expanded Quick Actions**: When a quick action is expanded, users can now switch between all providers that support that specific quick action, enhancing flexibility in provider selection
9
20
  - [all] **Quick Action Can Disable Lock**: Some quick actions can now decide to not lock the block when operating on a block. Examples are `CreateVariant` and `CombineImages`.
21
+ - [image-generation] **Ideogram V3**: Added support for Ideogram V3 provider for image generation, which supports text-to-image and image-to-image generation
10
22
 
11
23
  ## [0.2.2] - 2025-07-16
12
24
 
package/README.md CHANGED
@@ -156,6 +156,18 @@ Key features:
156
156
  - Configurable model selection (Claude 3.5 Sonnet, Claude 3.7 Sonnet, etc.)
157
157
  - Default model: Claude 3.7 Sonnet (2025-02-19)
158
158
 
159
+ **Custom Translations:**
160
+
161
+ ```typescript
162
+ cesdk.i18n.setTranslations({
163
+ en: {
164
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.prompt': 'Enter your text transformation request',
165
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.temperature': 'Claude Creativity Level',
166
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.maxTokens': 'Claude Response Length'
167
+ }
168
+ });
169
+ ```
170
+
159
171
  #### OpenAI GPT
160
172
 
161
173
  A powerful text generation model that handles various text transformations:
@@ -191,6 +203,87 @@ Key features:
191
203
  - Configurable model selection (GPT-4o, GPT-4o-mini, GPT-3.5-turbo, etc.)
192
204
  - Default model: GPT-4o-mini
193
205
 
206
+ **Custom Translations:**
207
+
208
+ ```typescript
209
+ cesdk.i18n.setTranslations({
210
+ en: {
211
+ 'ly.img.plugin-ai-text-generation-web.openai.property.prompt': 'Enter your text transformation request',
212
+ 'ly.img.plugin-ai-text-generation-web.openai.property.temperature': 'GPT Creativity Level',
213
+ 'ly.img.plugin-ai-text-generation-web.openai.property.maxTokens': 'GPT Response Length'
214
+ }
215
+ });
216
+ ```
217
+
218
+ ### Customizing Labels and Translations
219
+
220
+ You can customize all labels and text in the AI text generation interface using the translation system. This allows you to provide better labels for your users in any language.
221
+
222
+ #### Translation Key Structure
223
+
224
+ The system checks for translations in this order (highest to lowest priority):
225
+
226
+ 1. **Provider-specific**: `ly.img.plugin-ai-text-generation-web.${provider}.property.${field}` - Override labels for a specific AI provider
227
+ 2. **Generic**: `ly.img.plugin-ai-generation-web.property.${field}` - Override labels for all AI plugins
228
+
229
+ #### Basic Example
230
+
231
+ ```typescript
232
+ // Customize labels for your AI text generation interface
233
+ cesdk.i18n.setTranslations({
234
+ en: {
235
+ // Generic labels (applies to ALL AI plugins)
236
+ 'ly.img.plugin-ai-generation-web.property.prompt': 'Describe what you want to create',
237
+ 'ly.img.plugin-ai-generation-web.property.temperature': 'Creativity Level',
238
+ 'ly.img.plugin-ai-generation-web.property.maxTokens': 'Maximum Response Length',
239
+
240
+ // Provider-specific for Anthropic
241
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.prompt': 'Enter your text transformation prompt',
242
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.temperature': 'Response Creativity',
243
+ 'ly.img.plugin-ai-text-generation-web.anthropic.property.maxTokens': 'Max Response Length',
244
+
245
+ // Provider-specific for OpenAI
246
+ 'ly.img.plugin-ai-text-generation-web.openai.property.prompt': 'Describe your text transformation',
247
+ 'ly.img.plugin-ai-text-generation-web.openai.property.temperature': 'Creativity Setting',
248
+ 'ly.img.plugin-ai-text-generation-web.openai.property.maxTokens': 'Response Limit'
249
+ }
250
+ });
251
+ ```
252
+
253
+ #### QuickAction Translations
254
+
255
+ Text QuickActions (like "Improve Writing", "Fix Grammar", etc.) use their own translation keys:
256
+
257
+ ```typescript
258
+ cesdk.i18n.setTranslations({
259
+ en: {
260
+ // QuickAction button labels
261
+ 'ly.img.plugin-ai-text-generation-web.quickAction.improve': 'Improve Writing',
262
+ 'ly.img.plugin-ai-text-generation-web.quickAction.fix': 'Fix Grammar',
263
+ 'ly.img.plugin-ai-text-generation-web.quickAction.shorter': 'Make Shorter',
264
+ 'ly.img.plugin-ai-text-generation-web.quickAction.longer': 'Make Longer',
265
+ 'ly.img.plugin-ai-text-generation-web.quickAction.changeTone': 'Change Tone',
266
+ 'ly.img.plugin-ai-text-generation-web.quickAction.translate': 'Translate',
267
+ 'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo': 'Transform Text...',
268
+
269
+ // QuickAction input fields and buttons
270
+ 'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt': 'Transform Text...',
271
+ 'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.prompt.placeholder': 'e.g. "Convert to bullet points"',
272
+ 'ly.img.plugin-ai-text-generation-web.quickAction.changeTextTo.apply': 'Transform',
273
+
274
+ 'ly.img.plugin-ai-text-generation-web.quickAction.translate.language': 'Target Language',
275
+ 'ly.img.plugin-ai-text-generation-web.quickAction.translate.apply': 'Translate'
276
+ }
277
+ });
278
+ ```
279
+
280
+ **QuickAction Translation Structure:**
281
+ - Base key (e.g., `.quickAction.improve`): Button text when QuickAction is collapsed
282
+ - `.prompt`: Label for input field when expanded
283
+ - `.prompt.placeholder`: Placeholder text for input field
284
+ - `.apply`: Text for action/submit button
285
+ - Additional fields like `.language`: Custom field labels
286
+
194
287
  ### Configuration Options
195
288
 
196
289
  The plugin accepts the following configuration options:
@@ -410,6 +503,10 @@ cesdk.ui.setCanvasMenuOrder([
410
503
  ]);
411
504
  ```
412
505
 
506
+ ## Translations
507
+
508
+ For customization and localization, see the [translations.json](https://github.com/imgly/plugins/tree/main/packages/plugin-ai-text-generation-web/translations.json) file which contains provider-specific translation keys for text generation interfaces.
509
+
413
510
  ## Related Packages
414
511
 
415
512
  - [@imgly/plugin-ai-generation-web](https://github.com/imgly/plugins/tree/main/packages/plugin-ai-generation-web) - Core utilities for AI generation
@@ -1,19 +1,101 @@
1
- var j="0.39.0";var mt=!1,N,ze,Ht,Xt,Jt,gt,Kt,Se,Qe,yt,Ye,Pe,wt;function bt(s,e={auto:!1}){if(mt)throw new Error(`you must \`import '@anthropic-ai/sdk/shims/${s.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(N)throw new Error(`can't \`import '@anthropic-ai/sdk/shims/${s.kind}'\` after \`import '@anthropic-ai/sdk/shims/${N}'\``);mt=e.auto,N=s.kind,ze=s.fetch,Ht=s.Request,Xt=s.Response,Jt=s.Headers,gt=s.FormData,Kt=s.Blob,Se=s.File,Qe=s.ReadableStream,yt=s.getMultipartRequestOptions,Ye=s.getDefaultAgent,Pe=s.fileFromPath,wt=s.isFsReadStream}var Ae=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function _t({manuallyImported:s}={}){let e=s?"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,r,n,i;try{t=fetch,r=Request,n=Response,i=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:r,Response:n,Headers:i,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(o,a)=>({...a,body:new Ae(o)}),getDefaultAgent:o=>{},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:o=>!1}}N||bt(_t(),{auto:!0});var c=class extends Error{},p=class s extends c{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new v({message:r,cause:Me(t)});let i=t;return e===400?new ee(e,i,r,n):e===401?new te(e,i,r,n):e===403?new re(e,i,r,n):e===404?new se(e,i,r,n):e===409?new ne(e,i,r,n):e===422?new ie(e,i,r,n):e===429?new oe(e,i,r,n):e>=500?new ae(e,i,r,n):new s(e,i,r,n)}},g=class extends p{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},v=class extends p{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},X=class extends v{constructor({message:e}={}){super({message:e??"Request timed out."})}},ee=class extends p{},te=class extends p{},re=class extends p{},se=class extends p{},ne=class extends p{},ie=class extends p{},oe=class extends p{},ae=class extends p{};var Ee=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},U=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},_,k=class{constructor(){_.set(this,void 0),this.buffer=new Uint8Array,Ee(this,_,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;let n=[],i;for(;(i=zt(this.buffer,U(this,_,"f")))!=null;){if(i.carriage&&U(this,_,"f")==null){Ee(this,_,i.index,"f");continue}if(U(this,_,"f")!=null&&(i.index!==U(this,_,"f")+1||i.carriage)){n.push(this.decodeText(this.buffer.slice(0,U(this,_,"f")-1))),this.buffer=this.buffer.slice(U(this,_,"f")),Ee(this,_,null,"f");continue}let o=U(this,_,"f")!==null?i.preceding-1:i.preceding,a=this.decodeText(this.buffer.slice(0,o));n.push(a),this.buffer=this.buffer.slice(i.index),Ee(this,_,null,"f")}return n}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 c(`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 c(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new c("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
2
- `):[]}};_=new WeakMap;k.NEWLINE_CHARS=new Set([`
3
- `,"\r"]);k.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zt(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function xt(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}function ce(s){if(s[Symbol.asyncIterator])return s;let e=s.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 A=class s{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*n(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let o of Qt(e,t)){if(o.event==="completion")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event==="message_start"||o.event==="message_delta"||o.event==="message_stop"||o.event==="content_block_start"||o.event==="content_block_delta"||o.event==="content_block_stop")try{yield JSON.parse(o.data)}catch(a){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),a}if(o.event!=="ping"&&o.event==="error")throw p.generate(void 0,`SSE Error: ${o.data}`,o.data,et(e.headers))}i=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{i||t.abort()}}return new s(n,t)}static fromReadableStream(e,t){let r=!1;async function*n(){let o=new k,a=ce(e);for await(let h of a)for(let f of o.decode(h))yield f;for(let h of o.flush())yield h}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let a of n())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new s(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=i=>({next:()=>{if(i.length===0){let o=r.next();e.push(o),t.push(o)}return i.shift()}});return[new s(()=>n(e),this.controller),new s(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new Qe({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:o}=await t.next();if(o)return n.close();let a=r.encode(JSON.stringify(i)+`
4
- `);n.enqueue(a)}catch(i){n.error(i)}},async cancel(){await t.return?.()}})}};async function*Qt(s,e){if(!s.body)throw e.abort(),new c("Attempted to iterate over a response with no body");let t=new Ze,r=new k,n=ce(s.body);for await(let i of Yt(n))for(let o of r.decode(i)){let a=t.decode(o);a&&(yield a)}for(let i of r.flush()){let o=t.decode(i);o&&(yield o)}}async function*Yt(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let i;for(;(i=xt(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}var Ze=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 i={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Zt(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Zt(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}var er=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",tr=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ue(s),ue=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function";async function St(s,e,t){if(s=await s,tr(s))return s;if(er(s)){let n=await s.blob();e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=ue(n)?[await n.arrayBuffer()]:[n];return new Se(i,e,t)}let r=await rr(s);if(e||(e=nr(s)??"unknown_file"),!t?.type){let n=r[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new Se(r,e,t)}async function rr(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ue(s))e.push(await s.arrayBuffer());else if(ir(s))for await(let t of s)e.push(t);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${s?.constructor?.name}; props: ${sr(s)}`);return e}function sr(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function nr(s){return tt(s.name)||tt(s.filename)||tt(s.path)?.split(/[\\/]/).pop()}var tt=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},ir=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",rt=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody";var ar=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},cr=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},ke;async function kt(s){let{response:e}=s;if(s.options.stream)return J("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):A.fromSSEResponse(e,s.controller);if(e.status===204)return null;if(s.options.__binaryResponse)return e;let t=e.headers.get("content-type");if(t?.includes("application/json")||t?.includes("application/vnd.api+json")){let i=await e.json();return J("response",e.status,e.url,e.headers,i),Rt(i,e)}let n=await e.text();return J("response",e.status,e.url,e.headers,n),n}function Rt(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var Ie=class s extends Promise{constructor(e,t=kt){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new s(this.responsePromise,async t=>Rt(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)}},Te=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:i}){this.baseURL=e,this.maxRetries=st("maxRetries",t),this.timeout=st("timeout",r),this.httpAgent=n,this.fetch=i??ze}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...fr(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${yr()}`}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,r){return this.request(Promise.resolve(r).then(async n=>{let i=n&&ue(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:i}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}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:r,path:n,query:i,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:rt(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,h=this.calculateContentLength(a),f=this.buildURL(n,i);"timeout"in e&&st("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let b=e.httpAgent??this.httpAgent??Ye(f),B=e.timeout+1e3;typeof b?.options?.timeout=="number"&&B>(b.options.timeout??0)&&(b.options.timeout=B),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let xe=this.buildHeaders({options:e,headers:o,contentLength:h,retryCount:t});return{req:{method:r,...a&&{body:a},headers:xe,...b&&{agent:b},signal:e.signal??null},url:f,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let i={};r&&(i["content-length"]=r);let o=this.defaultHeaders(e);return Et(i,o),Et(i,t),rt(e.body)&&N!=="node"&&delete i["content-type"],Re(o,"x-stainless-retry-count")===void 0&&Re(t,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(n)),Re(o,"x-stainless-timeout")===void 0&&Re(t,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,t),i}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new c("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:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,n){return p.generate(e,t,r,n)}request(e,t=null){return new Ie(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(r);let{req:i,url:o,timeout:a}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(i,{url:o,options:r}),J("request",o,r,i.headers),r.signal?.aborted)throw new g;let h=new AbortController,f=await this.fetchWithTimeout(o,i,a,h).catch(Me);if(f instanceof Error){if(r.signal?.aborted)throw new g;if(t)return this.retryRequest(r,t);throw f.name==="AbortError"?new X:new v({cause:f})}let b=et(f.headers);if(!f.ok){if(t&&this.shouldRetry(f)){let Ge=`retrying, ${t} attempts remaining`;return J(`response (error; ${Ge})`,f.status,o,b),this.retryRequest(r,t,b)}let B=await f.text().catch(Ge=>Me(Ge).message),xe=hr(B),Ve=xe?void 0:B;throw J(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,f.status,o,b,Ve),this.makeStatusError(f.status,xe,Ve,b)}return{response:f,options:r,controller:h}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new nt(this,r,e)}buildURL(e,t){let r=mr(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return le(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new c(`Cannot stringify type ${typeof r}; 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,r,n){let{signal:i,...o}=t||{};i&&i.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r),h={signal:n.signal,...o};h.method&&(h.method=h.method.toUpperCase());let f=60*1e3,b=setTimeout(()=>{if(h&&h?.agent?.sockets)for(let B of Object.values(h?.agent?.sockets).flat())B?.setKeepAlive&&B.setKeepAlive(!0,f)},f);return this.fetch.call(void 0,e,h).finally(()=>{clearTimeout(a),clearTimeout(b)})}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,r){let n,i=r?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(n=a)}let o=r?.["retry-after"];if(o&&!n){let a=parseFloat(o);Number.isNaN(a)?n=Date.parse(o)-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 gr(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${j}`}},Be=class{constructor(e,t,r,n){ke.set(this,void 0),ar(this,ke,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new c("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 r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,i]of r)e.url.searchParams.set(n,i);t.query=void 0,t.path=e.url.toString()}return await cr(this,ke,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ke=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},nt=class extends Ie{constructor(e,t,r){super(t,async n=>new r(e,n.response,await kt(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},et=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),ur={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},x=s=>typeof s=="object"&&s!==null&&!le(s)&&Object.keys(s).every(e=>It(ur,e)),lr=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":At(Deno.build.os),"X-Stainless-Arch":Pt(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":j,"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":j,"X-Stainless-OS":At(process.platform),"X-Stainless-Arch":Pt(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let s=dr();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":j,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dr(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:e,version:`${n}.${i}.${o}`}}}return null}var Pt=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",At=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Mt,fr=()=>Mt??(Mt=lr()),hr=s=>{try{return JSON.parse(s)}catch{return}},pr=/^[a-z][a-z0-9+.-]*:/i,mr=s=>pr.test(s),gr=s=>new Promise(e=>setTimeout(e,s)),st=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new c(`${s} must be an integer`);if(e<0)throw new c(`${s} must be a positive integer`);return e},Me=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch{}return new Error(String(s))};var ve=s=>{if(typeof process<"u")return process.env?.[s]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(s)?.trim()};function le(s){if(!s)return!0;for(let e in s)return!1;return!0}function It(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Et(s,e){for(let t in e){if(!It(e,t))continue;let r=t.toLowerCase();if(!r)continue;let n=e[t];n===null?delete s[r]:n!==void 0&&(s[r]=n)}}function J(s,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Anthropic:DEBUG:${s}`,...e)}var yr=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),Tt=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",wr=s=>typeof s?.get=="function";var Re=(s,e)=>{let t=e.toLowerCase();if(wr(s)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,i,o)=>i+o.toUpperCase());for(let n of[e,t,e.toUpperCase(),r]){let i=s.get(n);if(i)return i}}for(let[r,n]of Object.entries(s))if(r.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 M=class extends Be{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.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 $=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}?beta=true`,t)}list(e={},t){return x(e)?this.list({},e):this._client.getAPIList("/v1/models?beta=true",K,{query:e,...t})}},K=class extends M{};$.BetaModelInfosPage=K;var V=class s{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new k;for await(let t of this.iterator)for(let r of e.decode(t))yield JSON.parse(r);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 c("Attempted to iterate over a response with no body");return new s(ce(e.body),t)}};var D=class extends m{create(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/batches?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}retrieve(e,t={},r){if(x(t))return this.retrieve(e,{},t);let{betas:n}=t;return this._client.get(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}list(e={},t){if(x(e))return this.list({},e);let{betas:r,...n}=e;return this._client.getAPIList("/v1/messages/batches?beta=true",G,{query:n,...t,headers:{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString(),...t?.headers}})}delete(e,t={},r){if(x(t))return this.delete(e,{},t);let{betas:n}=t;return this._client.delete(`/v1/messages/batches/${e}?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}cancel(e,t={},r){if(x(t))return this.cancel(e,{},t);let{betas:n}=t;return this._client.post(`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString(),...r?.headers}})}async results(e,t={},r){if(x(t))return this.results(e,{},t);let n=await this.retrieve(e);if(!n.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);let{betas:i}=t;return this._client.get(n.results_url,{...r,headers:{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...r?.headers},__binaryResponse:!0})._thenUnwrap((o,a)=>V.fromResponse(a.response,a.controller))}},G=class extends M{};D.BetaMessageBatchesPage=G;var Sr=s=>{let e=0,t=[];for(;e<s.length;){let r=s[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(r==="["){t.push({type:"paren",value:"["}),e++;continue}if(r==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(r===":"){t.push({type:"separator",value:":"}),e++;continue}if(r===","){t.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",h=!1;for(r=s[++e];r!=='"';){if(e===s.length){h=!0;break}if(r==="\\"){if(e++,e===s.length){h=!0;break}a+=r+s[e],r=s[++e]}else a+=r,r=s[++e]}r=s[++e],h||t.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=s[++e]);r&&i.test(r)||r===".";)a+=r,r=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(r&&o.test(r)){let a="";for(;r&&o.test(r)&&e!==s.length;)a+=r,r=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},z=s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),z(s);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),z(s);case"string":let r=s[s.length-2];if(r?.type==="delimiter")return s=s.slice(0,s.length-1),z(s);if(r?.type==="brace"&&r.value==="{")return s=s.slice(0,s.length-1),z(s);break;case"delimiter":return s=s.slice(0,s.length-1),z(s);break}return s},Pr=s=>{let e=[];return s.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==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},Ar=s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},Oe=s=>JSON.parse(Ar(Pr(z(Sr(s)))));var y=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},u=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},S,O,de,Ce,fe,he,qe,pe,R,me,Fe,je,Q,Ne,Ue,it,Bt,ot,at,ct,ut,vt,Ot="__json_buf",$e=class s{constructor(){S.add(this),this.messages=[],this.receivedMessages=[],O.set(this,void 0),this.controller=new AbortController,de.set(this,void 0),Ce.set(this,()=>{}),fe.set(this,()=>{}),he.set(this,void 0),qe.set(this,()=>{}),pe.set(this,()=>{}),R.set(this,{}),me.set(this,!1),Fe.set(this,!1),je.set(this,!1),Q.set(this,!1),Ne.set(this,void 0),Ue.set(this,void 0),ot.set(this,e=>{if(y(this,Fe,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new g),e instanceof g)return y(this,je,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),y(this,de,new Promise((e,t)=>{y(this,Ce,e,"f"),y(this,fe,t,"f")}),"f"),y(this,he,new Promise((e,t)=>{y(this,qe,e,"f"),y(this,pe,t,"f")}),"f"),u(this,de,"f").catch(()=>{}),u(this,he,"f").catch(()=>{})}get response(){return u(this,Ne,"f")}get request_id(){return u(this,Ue,"f")}async withResponse(){let e=await u(this,de,"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 s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new s;for(let i of t.messages)n._addMessageParam(i);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},u(this,ot,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),u(this,S,"m",at).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)u(this,S,"m",ct).call(this,a);if(o.controller.signal?.aborted)throw new g;u(this,S,"m",ut).call(this)}_connected(e){this.ended||(y(this,Ne,e,"f"),y(this,Ue,e?.headers.get("request-id"),"f"),u(this,Ce,"f").call(this,e),this._emit("connect"))}get ended(){return u(this,me,"f")}get errored(){return u(this,Fe,"f")}get aborted(){return u(this,je,"f")}abort(){this.controller.abort()}on(e,t){return(u(this,R,"f")[e]||(u(this,R,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,R,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(u(this,R,"f")[e]||(u(this,R,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{y(this,Q,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){y(this,Q,!0,"f"),await u(this,he,"f")}get currentMessage(){return u(this,O,"f")}async finalMessage(){return await this.done(),u(this,S,"m",it).call(this)}async finalText(){return await this.done(),u(this,S,"m",Bt).call(this)}_emit(e,...t){if(u(this,me,"f"))return;e==="end"&&(y(this,me,!0,"f"),u(this,qe,"f").call(this));let r=u(this,R,"f")[e];if(r&&(u(this,R,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!u(this,Q,"f")&&!r?.length&&Promise.reject(n),u(this,fe,"f").call(this,n),u(this,pe,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!u(this,Q,"f")&&!r?.length&&Promise.reject(n),u(this,fe,"f").call(this,n),u(this,pe,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",u(this,S,"m",it).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),u(this,S,"m",at).call(this),this._connected(null);let n=A.fromReadableStream(e,this.controller);for await(let i of n)u(this,S,"m",ct).call(this,i);if(n.controller.signal?.aborted)throw new g;u(this,S,"m",ut).call(this)}[(O=new WeakMap,de=new WeakMap,Ce=new WeakMap,fe=new WeakMap,he=new WeakMap,qe=new WeakMap,pe=new WeakMap,R=new WeakMap,me=new WeakMap,Fe=new WeakMap,je=new WeakMap,Q=new WeakMap,Ne=new WeakMap,Ue=new WeakMap,ot=new WeakMap,S=new WeakSet,it=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Bt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},at=function(){this.ended||y(this,O,void 0,"f")},ct=function(t){if(this.ended)return;let r=u(this,S,"m",vt).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.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(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{y(this,O,r,"f");break}case"content_block_start":case"message_delta":break}},ut=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=u(this,O,"f");if(!t)throw new c("request ended without sending any chunks");return y(this,O,void 0,"f"),t},vt=function(t){let r=u(this,O,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let n=r.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 i=n[Ot]||"";i+=t.delta.partial_json,Object.defineProperty(n,Ot,{value:i,enumerable:!1,writable:!0}),i&&(n.input=Oe(i))}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 r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new A(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Ct={"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"},C=class extends m{constructor(){super(...arguments),this.batches=new D(this._client)}create(e,t){let{betas:r,...n}=e;return n.model in Ct&&console.warn(`The model '${n.model}' is deprecated and will reach end-of-life on ${Ct[n.model]}
6
- 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:{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0,...t?.headers},stream:e.stream??!1})}stream(e,t){return $e.createMessage(this,e,t)}countTokens(e,t){let{betas:r,...n}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:n,...t,headers:{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString(),...t?.headers}})}};C.Batches=D;C.BetaMessageBatchesPage=G;var E=class extends m{constructor(){super(...arguments),this.models=new $(this._client),this.messages=new C(this._client)}};E.Models=$;E.BetaModelInfosPage=K;E.Messages=C;var L=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 x(e)?this.list({},e):this._client.getAPIList("/v1/messages/batches",Y,{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 r=await this.retrieve(e);if(!r.results_url)throw new c(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})._thenUnwrap((n,i)=>V.fromResponse(i.response,i.controller))}},Y=class extends M{};W.MessageBatchesPage=Y;var w=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},l=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},P,q,ge,De,ye,we,Le,be,I,_e,We,He,Z,Xe,Je,lt,qt,dt,ft,ht,pt,Ft,jt="__json_buf",Ke=class s{constructor(){P.add(this),this.messages=[],this.receivedMessages=[],q.set(this,void 0),this.controller=new AbortController,ge.set(this,void 0),De.set(this,()=>{}),ye.set(this,()=>{}),we.set(this,void 0),Le.set(this,()=>{}),be.set(this,()=>{}),I.set(this,{}),_e.set(this,!1),We.set(this,!1),He.set(this,!1),Z.set(this,!1),Xe.set(this,void 0),Je.set(this,void 0),dt.set(this,e=>{if(w(this,We,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new g),e instanceof g)return w(this,He,!0,"f"),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))}),w(this,ge,new Promise((e,t)=>{w(this,De,e,"f"),w(this,ye,t,"f")}),"f"),w(this,we,new Promise((e,t)=>{w(this,Le,e,"f"),w(this,be,t,"f")}),"f"),l(this,ge,"f").catch(()=>{}),l(this,we,"f").catch(()=>{})}get response(){return l(this,Xe,"f")}get request_id(){return l(this,Je,"f")}async withResponse(){let e=await l(this,ge,"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 s;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,r){let n=new s;for(let i of t.messages)n._addMessageParam(i);return n._run(()=>n._createMessage(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},l(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,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,P,"m",ft).call(this);let{response:i,data:o}=await e.create({...t,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(i);for await(let a of o)l(this,P,"m",ht).call(this,a);if(o.controller.signal?.aborted)throw new g;l(this,P,"m",pt).call(this)}_connected(e){this.ended||(w(this,Xe,e,"f"),w(this,Je,e?.headers.get("request-id"),"f"),l(this,De,"f").call(this,e),this._emit("connect"))}get ended(){return l(this,_e,"f")}get errored(){return l(this,We,"f")}get aborted(){return l(this,He,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,I,"f")[e]||(l(this,I,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,I,"f")[e];if(!r)return this;let n=r.findIndex(i=>i.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,I,"f")[e]||(l(this,I,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,Z,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,Z,!0,"f"),await l(this,we,"f")}get currentMessage(){return l(this,q,"f")}async finalMessage(){return await this.done(),l(this,P,"m",lt).call(this)}async finalText(){return await this.done(),l(this,P,"m",qt).call(this)}_emit(e,...t){if(l(this,_e,"f"))return;e==="end"&&(w(this,_e,!0,"f"),l(this,Le,"f").call(this));let r=l(this,I,"f")[e];if(r&&(l(this,I,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,Z,"f")&&!r?.length&&Promise.reject(n),l(this,ye,"f").call(this,n),l(this,be,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,Z,"f")&&!r?.length&&Promise.reject(n),l(this,ye,"f").call(this,n),l(this,be,"f").call(this,n),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",l(this,P,"m",lt).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,P,"m",ft).call(this),this._connected(null);let n=A.fromReadableStream(e,this.controller);for await(let i of n)l(this,P,"m",ht).call(this,i);if(n.controller.signal?.aborted)throw new g;l(this,P,"m",pt).call(this)}[(q=new WeakMap,ge=new WeakMap,De=new WeakMap,ye=new WeakMap,we=new WeakMap,Le=new WeakMap,be=new WeakMap,I=new WeakMap,_e=new WeakMap,We=new WeakMap,He=new WeakMap,Z=new WeakMap,Xe=new WeakMap,Je=new WeakMap,dt=new WeakMap,P=new WeakSet,lt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},qt=function(){if(this.receivedMessages.length===0)throw new c("stream ended without producing a Message with role=assistant");let t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0)throw new c("stream ended without producing a content block with type=text");return t.join(" ")},ft=function(){this.ended||w(this,q,void 0,"f")},ht=function(t){if(this.ended)return;let r=l(this,P,"m",Ft).call(this,t);switch(this._emit("streamEvent",t,r),t.type){case"content_block_delta":{let n=r.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(r),this._addMessage(r,!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{w(this,q,r,"f");break}case"content_block_start":case"message_delta":break}},pt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");let t=l(this,q,"f");if(!t)throw new c("request ended without sending any chunks");return w(this,q,void 0,"f"),t},Ft=function(t){let r=l(this,q,"f");if(t.type==="message_start"){if(r)throw new c(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!r)throw new c(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return r;case"message_delta":return r.stop_reason=t.delta.stop_reason,r.stop_sequence=t.delta.stop_sequence,r.usage.output_tokens=t.usage.output_tokens,r;case"content_block_start":return r.content.push(t.content_block),r;case"content_block_delta":{let n=r.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 i=n[jt]||"";i+=t.delta.partial_json,Object.defineProperty(n,jt,{value:i,enumerable:!1,writable:!0}),i&&(n.input=Oe(i))}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 r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("streamEvent",n=>{let i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new A(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var T=class extends m{constructor(){super(...arguments),this.batches=new W(this._client)}create(e,t){return e.model in Nt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Nt[e.model]}
7
- 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 Ke.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}},Nt={"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"};T.Batches=W;T.MessageBatchesPage=Y;var F=class extends m{retrieve(e,t){return this._client.get(`/v1/models/${e}`,t)}list(e={},t){return x(e)?this.list({},e):this._client.getAPIList("/v1/models",H,{query:e,...t})}},H=class extends M{};F.ModelInfosPage=H;var Ut,d=class extends Te{constructor({baseURL:e=ve("ANTHROPIC_BASE_URL"),apiKey:t=ve("ANTHROPIC_API_KEY")??null,authToken:r=ve("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){let i={apiKey:t,authToken:r,...n,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Tt())throw new c(`It looks like you're running in a browser-like environment.
1
+ var Br=typeof global=="object"&&global&&global.Object===Object&&global,rr=Br,Ur=typeof self=="object"&&self&&self.Object===Object&&self,Fr=rr||Ur||Function("return this")(),C=Fr,zr=C.Symbol,K=zr,ir=Object.prototype,qr=ir.hasOwnProperty,Vr=ir.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 i=!0}catch{}var n=Vr.call(r);return i&&(e?r[ce]=t:delete r[ce]),n}var Wr=Hr,Gr=Object.prototype,Qr=Gr.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)?Wr(r):Kr(r)}var he=Zr;function ei(r){return r!=null&&typeof r=="object"}var vt=ei,Ms=Array.isArray;function ti(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var nr=ti,ri="[object AsyncFunction]",ii="[object Function]",ni="[object GeneratorFunction]",oi="[object Proxy]";function si(r){if(!nr(r))return!1;var e=he(r);return e==ii||e==ni||e==ri||e==oi}var ai=si,li=C["__core-js_shared__"],ht=li,qt=function(){var r=/[^.]+$/.exec(ht&&ht.keys&&ht.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function ui(r){return!!qt&&qt in r}var ci=ui,di=Function.prototype,pi=di.toString;function fi(r){if(r!=null){try{return pi.call(r)}catch{}try{return r+""}catch{}}return""}var B=fi,hi=/[\\^$.*+?()[\]{}|]/g,gi=/^\[object .+?Constructor\]$/,mi=Function.prototype,yi=Object.prototype,bi=mi.toString,wi=yi.hasOwnProperty,xi=RegExp("^"+bi.call(wi).replace(hi,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ki(r){if(!nr(r)||ci(r))return!1;var e=ai(r)?xi:gi;return e.test(B(r))}var vi=ki;function _i(r,e){return r?.[e]}var Ai=_i;function Si(r,e){var t=Ai(r,e);return vi(t)?t:void 0}var J=Si,Mi=J(C,"WeakMap"),yt=Mi;function Ii(r,e){return r===e||r!==r&&e!==e}var Ei=Ii,Ci=9007199254740991;function Pi(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=Ci}var Ti=Pi,Is=Object.prototype,$i="[object Arguments]";function ji(r){return vt(r)&&he(r)==$i}var Vt=ji,or=Object.prototype,Ri=or.hasOwnProperty,Li=or.propertyIsEnumerable,Es=Vt(function(){return arguments}())?Vt:function(r){return vt(r)&&Ri.call(r,"callee")&&!Li.call(r,"callee")},sr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ht=sr&&typeof module=="object"&&module&&!module.nodeType&&module,Ni=Ht&&Ht.exports===sr,Wt=Ni?C.Buffer:void 0,Cs=Wt?Wt.isBuffer:void 0,Oi="[object Arguments]",Di="[object Array]",Bi="[object Boolean]",Ui="[object Date]",Fi="[object Error]",zi="[object Function]",qi="[object Map]",Vi="[object Number]",Hi="[object Object]",Wi="[object RegExp]",Gi="[object Set]",Qi="[object String]",Yi="[object WeakMap]",Ki="[object ArrayBuffer]",Ji="[object DataView]",Xi="[object Float32Array]",Zi="[object Float64Array]",en="[object Int8Array]",tn="[object Int16Array]",rn="[object Int32Array]",nn="[object Uint8Array]",on="[object Uint8ClampedArray]",sn="[object Uint16Array]",an="[object Uint32Array]",p={};p[Xi]=p[Zi]=p[en]=p[tn]=p[rn]=p[nn]=p[on]=p[sn]=p[an]=!0;p[Oi]=p[Di]=p[Ki]=p[Bi]=p[Ji]=p[Ui]=p[Fi]=p[zi]=p[qi]=p[Vi]=p[Hi]=p[Wi]=p[Gi]=p[Qi]=p[Yi]=!1;function ln(r){return vt(r)&&Ti(r.length)&&!!p[he(r)]}var un=ln;function cn(r){return function(e){return r(e)}}var dn=cn,ar=typeof exports=="object"&&exports&&!exports.nodeType&&exports,de=ar&&typeof module=="object"&&module&&!module.nodeType&&module,pn=de&&de.exports===ar,gt=pn&&rr.process,fn=function(){try{var r=de&&de.require&&de.require("util").types;return r||gt&&gt.binding&&gt.binding("util")}catch{}}(),Gt=fn,Qt=Gt&&Gt.isTypedArray,Ps=Qt?dn(Qt):un,hn=Object.prototype,Ts=hn.hasOwnProperty;function gn(r,e){return function(t){return r(e(t))}}var mn=gn,$s=mn(Object.keys,Object),yn=Object.prototype,js=yn.hasOwnProperty,bn=J(Object,"create"),pe=bn;function wn(){this.__data__=pe?pe(null):{},this.size=0}var xn=wn;function kn(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var vn=kn,_n="__lodash_hash_undefined__",An=Object.prototype,Sn=An.hasOwnProperty;function Mn(r){var e=this.__data__;if(pe){var t=e[r];return t===_n?void 0:t}return Sn.call(e,r)?e[r]:void 0}var In=Mn,En=Object.prototype,Cn=En.hasOwnProperty;function Pn(r){var e=this.__data__;return pe?e[r]!==void 0:Cn.call(e,r)}var Tn=Pn,$n="__lodash_hash_undefined__";function jn(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=pe&&e===void 0?$n:e,this}var Rn=jn;function X(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}X.prototype.clear=xn;X.prototype.delete=vn;X.prototype.get=In;X.prototype.has=Tn;X.prototype.set=Rn;var Yt=X;function Ln(){this.__data__=[],this.size=0}var Nn=Ln;function On(r,e){for(var t=r.length;t--;)if(Ei(r[t][0],e))return t;return-1}var Oe=On,Dn=Array.prototype,Bn=Dn.splice;function Un(r){var e=this.__data__,t=Oe(e,r);if(t<0)return!1;var i=e.length-1;return t==i?e.pop():Bn.call(e,t,1),--this.size,!0}var Fn=Un;function zn(r){var e=this.__data__,t=Oe(e,r);return t<0?void 0:e[t][1]}var qn=zn;function Vn(r){return Oe(this.__data__,r)>-1}var Hn=Vn;function Wn(r,e){var t=this.__data__,i=Oe(t,r);return i<0?(++this.size,t.push([r,e])):t[i][1]=e,this}var Gn=Wn;function Z(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}Z.prototype.clear=Nn;Z.prototype.delete=Fn;Z.prototype.get=qn;Z.prototype.has=Hn;Z.prototype.set=Gn;var De=Z,Qn=J(C,"Map"),fe=Qn;function Yn(){this.size=0,this.__data__={hash:new Yt,map:new(fe||De),string:new Yt}}var Kn=Yn;function Jn(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Xn=Jn;function Zn(r,e){var t=r.__data__;return Xn(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Be=Zn;function eo(r){var e=Be(this,r).delete(r);return this.size-=e?1:0,e}var to=eo;function ro(r){return Be(this,r).get(r)}var io=ro;function no(r){return Be(this,r).has(r)}var oo=no;function so(r,e){var t=Be(this,r),i=t.size;return t.set(r,e),this.size+=t.size==i?0:1,this}var ao=so;function ee(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var i=r[e];this.set(i[0],i[1])}}ee.prototype.clear=Kn;ee.prototype.delete=to;ee.prototype.get=io;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 i=t.__data__;if(!fe||i.length<yo-1)return i.push([r,e]),this.size=++t.size,this;t=this.__data__=new lr(i)}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,Rs=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=B(bt),Mo=B(fe),Io=B(wt),Eo=B(xt),Co=B(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,i=t?B(t):"";if(i)switch(i){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 $o=To;function jo(r){return this.__data__.has(r)}var Ro=jo;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=$o;kt.prototype.has=Ro;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,Bs=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Us=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[i,n]of Object.entries(e))n===!1||n===null||n===void 0?delete t[i]:n===!0?i in r||(t[i]=!0):t[i]=n;return t}var mt="@imgly/plugin-ai-generation",zs=`
2
+ <svg>
3
+ <symbol
4
+ fill="none"
5
+ xmlns="http://www.w3.org/2000/svg"
6
+ viewBox="0 0 24 24"
7
+ id="@imgly/Sparkle"
8
+ >
9
+ <path d="M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z" fill="currentColor"/>
10
+ <path d="M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9632 11.7642L18.9207 9.21086C18.9709 9.077 19.0765 8.97138 19.2104 8.92118L21.7637 7.96366C22.192 7.80307 22.192 7.1973 21.7637 7.0367L19.2104 6.07918C19.0765 6.02899 18.9709 5.92337 18.9207 5.78951L17.9632 3.23614Z" fill="currentColor"/>
11
+ <path d="M9.30058 7.82012C9.54712 7.1791 10.454 7.1791 10.7006 7.82012L12.3809 12.189C12.4571 12.3871 12.6136 12.5436 12.8117 12.6198L17.1806 14.3001C17.8216 14.5466 17.8216 15.4536 17.1806 15.7001L12.8117 17.3804C12.6136 17.4566 12.4571 17.6131 12.3809 17.8112L10.7006 22.1801C10.454 22.8211 9.54712 22.8211 9.30058 22.1801L7.62024 17.8112C7.54406 17.6131 7.38754 17.4566 7.18947 17.3804L2.82061 15.7001C2.17959 15.4536 2.17959 14.5466 2.82061 14.3001L7.18947 12.6198C7.38754 12.5436 7.54406 12.3871 7.62024 12.189L9.30058 7.82012Z" fill="currentColor"/>
12
+
13
+ </symbol>
14
+
15
+ <symbol
16
+ fill="none"
17
+ xmlns="http://www.w3.org/2000/svg"
18
+ viewBox="0 0 24 24"
19
+ id="${mt}/image"
20
+ >
21
+ <path d="M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z" fill="currentColor"/>
22
+ <path d="M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z" fill="currentColor"/>
23
+ <path d="M6.40053 5.38488C6.52538 5.06832 6.97338 5.06832 7.09823 5.38488L8.17455 8.11392C8.21267 8.21057 8.28917 8.28707 8.38582 8.32519L11.1149 9.40151C11.4314 9.52636 11.4314 9.97436 11.1149 10.0992L8.38582 11.1755C8.28917 11.2136 8.21267 11.2901 8.17455 11.3868L7.09823 14.1158C6.97338 14.4324 6.52538 14.4324 6.40053 14.1158L5.32421 11.3868C5.2861 11.2901 5.20959 11.2136 5.11295 11.1755L2.3839 10.0992C2.06735 9.97436 2.06735 9.52636 2.3839 9.40151L5.11295 8.32519C5.20959 8.28707 5.2861 8.21057 5.32421 8.11392L6.40053 5.38488Z" fill="currentColor"/>
24
+ <path d="M18.9994 16.5008V18.0004C18.9994 18.5526 18.5517 19.0004 17.9994 19.0004H9.33302L14.3753 11.4369C14.6722 10.9916 15.3266 10.9916 15.6234 11.4369L18.9994 16.5008Z" fill="currentColor"/>
25
+
26
+ </symbol>
27
+ <symbol
28
+ fill="none"
29
+ xmlns="http://www.w3.org/2000/svg"
30
+ viewBox="0 0 24 24"
31
+ id="${mt}/video"
32
+ >
33
+ <path d="M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z" fill="currentColor"/>
34
+ <path d="M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z" fill="currentColor"/>
35
+ <path d="M18.9019 3.3845C19.0267 3.06795 19.4747 3.06795 19.5996 3.3845L20.6759 6.11355C20.714 6.2102 20.7905 6.2867 20.8872 6.32482L23.6162 7.40114C23.9328 7.52598 23.9328 7.97399 23.6162 8.09883L20.8872 9.17515C20.7905 9.21327 20.714 9.28977 20.6759 9.38642L19.5996 12.1155C19.4747 12.432 19.0267 12.432 18.9019 12.1155L17.8255 9.38642C17.7874 9.28977 17.7109 9.21327 17.6143 9.17515L14.8852 8.09883C14.5687 7.97399 14.5687 7.52598 14.8852 7.40114L17.6143 6.32482C17.7109 6.2867 17.7874 6.2102 17.8255 6.11355L18.9019 3.3845Z" fill="currentColor"/>
36
+ <path d="M14.9994 13.2862C15.5089 12.8859 15.5089 12.1141 14.9995 11.7137L10.618 8.27047C9.96188 7.75485 9.00011 8.22225 9.00011 9.05673L9.00011 15.9429C9.00011 16.7773 9.96185 17.2448 10.618 16.7292L14.9994 13.2862Z" fill="currentColor"/>
37
+ </symbol>
38
+ <symbol
39
+ fill="none"
40
+ xmlns="http://www.w3.org/2000/svg"
41
+ viewBox="0 0 24 24"
42
+ id="${mt}/audio"
43
+ >
44
+ <path d="M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z" fill="currentColor"/>
45
+ <path d="M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z" fill="currentColor"/>
46
+ <path d="M19.5996 4.3845C19.4747 4.06795 19.0267 4.06795 18.9019 4.3845L17.8255 7.11355C17.7874 7.2102 17.7109 7.2867 17.6143 7.32482L14.8852 8.40114C14.5687 8.52598 14.5687 8.97399 14.8852 9.09883L17.6143 10.1752C17.7109 10.2133 17.7874 10.2898 17.8255 10.3864L18.9019 13.1155C19.0267 13.432 19.4747 13.432 19.5996 13.1155L20.6759 10.3864C20.714 10.2898 20.7905 10.2133 20.8872 10.1752L23.6162 9.09883C23.9328 8.97399 23.9328 8.52598 23.6162 8.40114L20.8872 7.32482C20.7905 7.2867 20.714 7.2102 20.6759 7.11355L19.5996 4.3845Z" fill="currentColor"/>
47
+ </symbol>
48
+ <symbol
49
+ fill="none"
50
+ xmlns="http://www.w3.org/2000/svg"
51
+ viewBox="0 0 24 24"
52
+ id="@imgly/MixingPlate"
53
+ >
54
+ <path d="M9.75 9C10.5784 9 11.25 8.32843 11.25 7.5C11.25 6.67157 10.5784 6 9.75 6C8.92157 6 8.25 6.67157 8.25 7.5C8.25 8.32843 8.92157 9 9.75 9Z" fill="currentColor"/>
55
+ <path d="M7 13C7.82843 13 8.5 12.3284 8.5 11.5C8.5 10.6716 7.82843 10 7 10C6.17157 10 5.5 10.6716 5.5 11.5C5.5 12.3284 6.17157 13 7 13Z" fill="currentColor"/>
56
+ <path d="M15.75 7.5C15.75 8.32843 15.0784 9 14.25 9C13.4216 9 12.75 8.32843 12.75 7.5C12.75 6.67157 13.4216 6 14.25 6C15.0784 6 15.75 6.67157 15.75 7.5Z" fill="currentColor"/>
57
+ <path d="M17 13C17.8284 13 18.5 12.3284 18.5 11.5C18.5 10.6716 17.8284 10 17 10C16.1716 10 15.5 10.6716 15.5 11.5C15.5 12.3284 16.1716 13 17 13Z" fill="currentColor"/>
58
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M8.26309 2.77709C10.6681 1.77921 13.4829 1.7322 15.9209 2.64297C18.1572 3.47923 20.0876 5.09285 21.1766 7.28598C22.3395 9.62772 22.4889 13.1077 20.3864 15.2982C19.2693 16.4621 17.7657 16.9982 16.0026 16.9997C15.7897 16.9997 15.5555 16.9864 15.3497 16.9745C15.309 16.9722 15.2694 16.9699 15.2313 16.9679C14.9817 16.9542 14.761 16.9455 14.5569 16.9539C14.124 16.9718 13.9598 17.0612 13.89 17.1324C13.718 17.3081 13.6946 17.6672 13.8854 17.8895C14.2899 18.3608 14.5016 18.9277 14.5016 19.5497C14.5016 20.2206 14.3086 20.9011 13.7542 21.3896C13.2471 21.837 12.6082 21.9997 11.9635 21.9997C10.6049 21.9997 9.31155 21.7367 8.0934 21.2067C6.89058 20.6831 5.84501 19.9687 4.94363 19.0666C4.04281 18.1651 3.31836 17.107 2.79369 15.8978C1.72761 13.4409 1.72662 10.5261 2.81247 8.07034C3.88024 5.65548 5.84206 3.78161 8.26309 2.77709ZM15.2207 4.51639C13.2556 3.78239 10.9651 3.82132 9.02956 4.62439C7.06888 5.43791 5.49559 6.94785 4.64163 8.87914C3.78373 10.8194 3.78253 13.1522 4.62841 15.1017C5.05312 16.0805 5.63511 16.9291 6.35838 17.6529C7.08102 18.3761 7.91671 18.9484 8.89123 19.3728C9.8492 19.7895 10.87 19.9997 11.9635 19.9997C12.2815 19.9997 12.394 19.9225 12.431 19.8899L12.4319 19.8891C12.4367 19.8849 12.4487 19.8743 12.4631 19.8359C12.4799 19.7911 12.5016 19.7024 12.5016 19.5497C12.5016 19.4091 12.4633 19.3034 12.3677 19.192C11.5353 18.222 11.5272 16.6868 12.4611 15.7331C13.0741 15.1071 13.8844 14.98 14.4745 14.9556C14.7819 14.943 15.085 14.9568 15.3409 14.9709C15.3906 14.9736 15.4379 14.9763 15.4832 14.9788C15.6876 14.9904 15.8508 14.9997 16.0009 14.9997C17.3405 14.9986 18.2792 14.6054 18.9435 13.9133C20.2633 12.5382 20.3186 10.055 19.3853 8.1755C18.5436 6.48051 17.0293 5.19281 15.2207 4.51639Z" fill="currentColor"/>
59
+
60
+ </symbol>
61
+ </svg>
62
+ `;var U="0.39.0";var cr=!1,F,_t,Oo,Do,Bo,dr,Uo,Ue,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,Bo=r.Headers,dr=r.FormData,Uo=r.Blob,Ue=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,i,n,o;try{t=fetch,i=Request,n=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:i,Response:n,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,i,n){super(`${r.makeMessage(e,t,i)}`),this.status=e,this.headers=n,this.request_id=n?.["request-id"],this.error=t}static makeMessage(e,t,i){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):i;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,i,n){if(!e||!n)return new R({message:i,cause:qe(t)});let o=t;return e===400?new me(e,o,i,n):e===401?new ye(e,o,i,n):e===403?new be(e,o,i,n):e===404?new we(e,o,i,n):e===409?new xe(e,o,i,n):e===422?new ke(e,o,i,n):e===429?new ve(e,o,i,n):e>=500?new _e(e,o,i,n):new r(e,o,i,n)}},y=class extends g{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},R=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 R{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,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},z=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)},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,i=new Uint8Array(this.buffer.length+t.length);i.set(this.buffer),i.set(t,this.buffer.length),this.buffer=i;let n=[],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)){n.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));n.push(a),this.buffer=this.buffer.slice(o.index),Ve(this,k,null,"f")}return n}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
+ `):[]}};k=new WeakMap;P.NEWLINE_CHARS=new Set([`
64
+ `,"\r"]);P.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function qo(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function mr(r){for(let i=0;i<r.length-1;i++){if(r[i]===10&&r[i+1]===10||r[i]===13&&r[i+1]===13)return i+2;if(r[i]===13&&r[i+1]===10&&i+3<r.length&&r[i+2]===13&&r[i+3]===10)return i+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 i=!1;async function*n(){if(i)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!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(n,t)}static fromReadableStream(e,t){let i=!1;async function*n(){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(i)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{for await(let a of n())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=[],i=this.iterator(),n=o=>({next:()=>{if(o.length===0){let s=i.next();e.push(s),t.push(s)}return o.shift()}});return[new r(()=>n(e),this.controller),new r(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,i=new TextEncoder;return new At({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=i.encode(JSON.stringify(o)+`
65
+ `);n.enqueue(a)}catch(o){n.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,i=new P,n=Ae(r.body);for await(let o of Ho(n))for(let s of i.decode(o)){let a=t.decode(s);a&&(yield a)}for(let o of i.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 i=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+i.length);n.set(e),n.set(i,e.length),e=n;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,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})}},jr={"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"};j.Batches=W;j.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",G,{query:e,...t})}},G=class extends I{};D.ModelInfosPage=G;var Rr,d=class extends Qe{constructor({baseURL:e=Ke("ANTHROPIC_BASE_URL"),apiKey:t=Ke("ANTHROPIC_API_KEY")??null,authToken:i=Ke("ANTHROPIC_AUTH_TOKEN")??null,...n}={}){let o={apiKey:t,authToken:i,...n,baseURL:e||"https://api.anthropic.com"};if(!o.dangerouslyAllowBrowser&&Sr())throw new l(`It looks like you're running in a browser-like environment.
8
69
 
9
70
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
71
  If you understand the risks and have appropriate mitigations in place,
11
72
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
73
 
13
74
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
14
- `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new L(this),this.messages=new T(this),this.models=new F(this),this.beta=new E(this),this._options=i,this.apiKey=t,this.authToken=r}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),r=this.bearerAuth(e);return t!=null&&!le(t)?t:r!=null&&!le(r)?r:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};Ut=d;d.Anthropic=Ut;d.HUMAN_PROMPT=`
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 j(this),this.models=new D(this),this.beta=new E(this),this._options=o,this.apiKey=t,this.authToken=i}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),i=this.bearerAuth(e);return t!=null&&!Me(t)?t:i!=null&&!Me(i)?i:{}}apiKeyAuth(e){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(e){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};Rr=d;d.Anthropic=Rr;d.HUMAN_PROMPT=`
15
76
 
16
77
  Human:`;d.AI_PROMPT=`
17
78
 
18
- Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=c;d.APIError=p;d.APIConnectionError=v;d.APIConnectionTimeoutError=X;d.APIUserAbortError=g;d.NotFoundError=se;d.ConflictError=ne;d.RateLimitError=oe;d.BadRequestError=ee;d.AuthenticationError=te;d.InternalServerError=ae;d.PermissionDeniedError=re;d.UnprocessableEntityError=ie;d.toFile=St;d.fileFromPath=Pe;d.Completions=L;d.Messages=T;d.Models=F;d.ModelInfosPage=H;d.Beta=E;var{HUMAN_PROMPT:ln,AI_PROMPT:dn}=d,$t=d;var Rr={model:"claude-3-7-sonnet-20250219",max_tokens:8192,temperature:.1},Dt={headers:{"x-api-key":null,authorization:null}};async function Ir(s,e,t,r){let n={};e.model&&(n.model=e.model),e.maxTokens&&(n.max_tokens=e.maxTokens),e.temperature&&(n.temperature=e.temperature);let i=await s.messages.create({...Rr,...n,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:r,...Dt,headers:{...Dt.headers??{},...e.headers}});async function*o(){try{for await(let a of i)a.type==="content_block_delta"&&a.delta.type==="text_delta"&&(yield a.delta.text)}catch(a){throw console.error("Stream error:",a),a}}return o()}var Lt=Ir;function Wt(s){return()=>{let e=null,t={kind:"text",id:"anthropic",name:"Anthropic",initialize:async()=>{e=new $t({dangerouslyAllowBrowser:!0,baseURL:s.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{supported:{"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":{}}}},output:{middleware:s.middlewares??s.middleware??[],generate:async({prompt:r,blockId:n},{engine:i,abortSignal:o})=>{if(e==null)throw new Error("Anthropic SDK is not initialized");if(n!=null&&i.block.getType(n)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it most be a text block");s.debug&&console.log("Sending prompt to Anthropic:",JSON.stringify(r,void 0,2));let a=await Lt(e,{proxyUrl:s.proxyUrl,headers:s.headers,model:s.model??"claude-3-7-sonnet-20250219"},r,o);async function*h(){let f="";for await(let b of a){if(o?.aborted)break;f+=b,yield{kind:"text",text:f}}return{kind:"text",text:f}}return h()}}};return Promise.resolve(t)}}var Tr={AnthropicProvider:Wt},wn=Tr;export{wn as default};
79
+ Assistant:`;d.DEFAULT_TIMEOUT=6e5;d.AnthropicError=l;d.APIError=g;d.APIConnectionError=R;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=j;d.Models=D;d.ModelInfosPage=G;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,i){let n={};e.model&&(n.model=e.model),e.maxTokens&&(n.max_tokens=e.maxTokens),e.temperature&&(n.temperature=e.temperature);let o=await r.messages.create({...ks,...n,stream:!0,messages:[{role:"user",content:[{type:"text",text:t}]}]},{signal:i,...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,i=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),n={kind:"text",id:"anthropic",name:"Anthropic",initialize:async()=>{e=new Lr({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:null,authToken:null})},input:{quickActions:{supported:i}},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(n)}}var _s={AnthropicProvider:Dr},Cl=_s;export{Cl as default};
80
+ /*! Bundled license information:
81
+
82
+ @imgly/plugin-ai-generation-web/dist/index.mjs:
83
+ (*! Bundled license information:
84
+
85
+ @imgly/plugin-utils/dist/index.mjs:
86
+ (*! Bundled license information:
87
+
88
+ lodash-es/lodash.js:
89
+ (**
90
+ * @license
91
+ * Lodash (Custom Build) <https://lodash.com/>
92
+ * Build: `lodash modularize exports="es" -o ./`
93
+ * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
94
+ * Released under MIT license <https://lodash.com/license>
95
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
96
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
97
+ *)
98
+ *)
99
+ *)
100
+ */
19
101
  //# sourceMappingURL=index.mjs.map