sliccy 2.22.2 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/node-server/index.js +136 -18
  2. package/dist/node-server/release-package.d.ts +0 -1
  3. package/dist/node-server/release-package.js +1 -8
  4. package/dist/ui/assets/{anthropic-CePl-niV.js → anthropic-5EX06qre.js} +4 -4
  5. package/dist/ui/assets/azure-openai-responses-B7etwOzk.js +1 -0
  6. package/dist/ui/assets/{dist-DEU7LMsW.js → dist-BETSJsV5.js} +1 -1
  7. package/dist/ui/assets/{dist-DY89ppnG.js → dist-BVxswsnA.js} +2 -2
  8. package/dist/ui/assets/{dist-Bsu1jCSL.js → dist-C_pwrhfY.js} +1 -1
  9. package/dist/ui/assets/{dist-UfV1NDbo.js → dist-Ck3Vla0r.js} +1 -1
  10. package/dist/ui/assets/{dist-DfXP7YfQ.js → dist-DB19jrs9.js} +1 -1
  11. package/dist/ui/assets/{es-Ctukg7Pf.js → es-CUZJ3cwV.js} +1 -1
  12. package/dist/ui/assets/{fs-C0vsW7YS.js → fs-BOiXGVkS.js} +2 -2
  13. package/dist/ui/assets/google-eMKt6D5q.js +1 -0
  14. package/dist/ui/assets/google-shared-tCK79d6s.js +11 -0
  15. package/dist/ui/assets/google-vertex-DVupsUV0.js +1 -0
  16. package/dist/ui/assets/{index-n7dM8Ny6.js → index-hy37TrIH.js} +1021 -941
  17. package/dist/ui/assets/{magick-wasm-CNSmo9gu.js → magick-wasm-DpuDwl7G.js} +1 -1
  18. package/dist/ui/assets/{mistral-DPFFr-1D.js → mistral-B1K_Jm8q.js} +4 -4
  19. package/dist/ui/assets/{onboarding-orchestrator-DX-WA9oh.js → onboarding-orchestrator-C2Vl3mDg.js} +1 -1
  20. package/dist/ui/assets/openai-codex-responses-Bax3P3Se.js +7 -0
  21. package/dist/ui/assets/openai-completions-MdSXoOj2.js +5 -0
  22. package/dist/ui/assets/openai-responses-Cx3_UA9r.js +1 -0
  23. package/dist/ui/assets/provider-settings-DdDjJ0n3.js +95 -0
  24. package/dist/ui/assets/simple-options-CDIijiMb.js +1 -0
  25. package/dist/ui/assets/{skills-Cp2_zExC.js → skills-D15e98qd.js} +1 -1
  26. package/dist/ui/assets/{slicc-editor-Bv8eZLtW.js → slicc-editor-C9a_yd9R.js} +2 -2
  27. package/dist/ui/index.html +16 -13
  28. package/dist/ui/llm-proxy-sw.js +1 -0
  29. package/dist/ui/packages/webapp/index.html +16 -13
  30. package/package.json +4 -3
  31. package/dist/node-server/sync-release-version.d.ts +0 -4
  32. package/dist/node-server/sync-release-version.js +0 -44
  33. package/dist/ui/assets/azure-openai-responses-B0ars-Hm.js +0 -1
  34. package/dist/ui/assets/google-CgTHsA2_.js +0 -1
  35. package/dist/ui/assets/google-shared-nj0IYXjb.js +0 -11
  36. package/dist/ui/assets/google-vertex-cqyT1zM2.js +0 -1
  37. package/dist/ui/assets/openai-codex-responses-DjTLNv18.js +0 -7
  38. package/dist/ui/assets/openai-completions-BnCyVXK7.js +0 -5
  39. package/dist/ui/assets/openai-responses-9MflKa27.js +0 -1
  40. package/dist/ui/assets/openai-responses-shared-D8Vix6-m.js +0 -10
  41. package/dist/ui/assets/provider-settings-DY_N8CBx.js +0 -95
  42. package/dist/ui/assets/sanitize-unicode-BD2XKRoV.js +0 -1
  43. package/dist/ui/assets/simple-options-CRMUB9za.js +0 -1
  44. /package/dist/ui/assets/{addon-fit-_YHcqy0h.js → addon-fit-CniRnSyE.js} +0 -0
  45. /package/dist/ui/assets/{browser-Cl7Q1LkV.js → browser-CFDl2kC3.js} +0 -0
  46. /package/dist/ui/assets/{bsh-watchdog-5FY6DxLX.js → bsh-watchdog-DWN1spIr.js} +0 -0
  47. /package/dist/ui/assets/{chat-fixture-Dp2mIM1B.js → chat-fixture-BGLmPevX.js} +0 -0
  48. /package/dist/ui/assets/{db-CDfQGWkv.js → db-QbwB670D.js} +0 -0
  49. /package/dist/ui/assets/{dist-BByiYVMV.js → dist-CkF25Z3T.js} +0 -0
  50. /package/dist/ui/assets/{dist-D6ztLqPA.js → dist-uJp2dR6X.js} +0 -0
  51. /package/dist/ui/assets/{fetch-body-DJGM6_Jl.js → fetch-body-DPMYsjzA.js} +0 -0
  52. /package/dist/ui/assets/{github-copilot-headers-B6Fvsk-Y.js → github-copilot-headers-DGaOrqaW.js} +0 -0
  53. /package/dist/ui/assets/{global-db-D767Oa4m.js → global-db-Cui6Md0w.js} +0 -0
  54. /package/dist/ui/assets/{hash-Dit8ENAX.js → hash-BN8UQrrC.js} +0 -0
  55. /package/dist/ui/assets/{headers-DkHU-pcw.js → headers-qDMOQQGF.js} +0 -0
  56. /package/dist/ui/assets/{lick-manager-proxy-DYlDsj9K.js → lick-manager-proxy-Dw3D3AzG.js} +0 -0
  57. /package/dist/ui/assets/{oauth-service-CKR4S63v.js → oauth-service-DUXASG7L.js} +0 -0
  58. /package/dist/ui/assets/{offscreen-client-BM0UHxmA.js → offscreen-client-DRN1fwvT.js} +0 -0
  59. /package/dist/ui/assets/{openai-CQsomflW.js → openai-D4NSaQIs.js} +0 -0
  60. /package/dist/ui/assets/{path-utils-CNNVZ3-O.js → path-utils-DAY6ORUp.js} +0 -0
  61. /package/dist/ui/assets/{pdfjs-BGlny-4w.js → pdfjs-C0bwNEC1.js} +0 -0
  62. /package/dist/ui/assets/{pyodide-B0OcGzKl.js → pyodide-DCMrvZhT.js} +0 -0
  63. /package/dist/ui/assets/{rum-C22a_afY.js → rum-sVedwbc1.js} +0 -0
  64. /package/dist/ui/assets/{secret-masking-D8cHWx2y.js → secret-masking-ZNVanUmG.js} +0 -0
  65. /package/dist/ui/assets/{sql-wasm-BaMgQAJZ.js → sql-wasm-GAMLdFdJ.js} +0 -0
  66. /package/dist/ui/assets/{src-Bd0ucr8W.js → src-DSYf97Eh.js} +0 -0
  67. /package/dist/ui/assets/{xterm-GX0WTpdZ.js → xterm-BaLOnk9X.js} +0 -0
@@ -4,6 +4,8 @@ import { createServer as createNetServer } from 'net';
4
4
  import { spawn } from 'child_process';
5
5
  import { existsSync, readFileSync } from 'fs';
6
6
  import { join, resolve } from 'path';
7
+ import { Readable, Transform } from 'stream';
8
+ import { StringDecoder } from 'string_decoder';
7
9
  import { fileURLToPath } from 'url';
8
10
  import express from 'express';
9
11
  import { WebSocketServer, WebSocket } from 'ws';
@@ -831,6 +833,10 @@ async function main() {
831
833
  res.status(400).json({ error: 'Missing X-Target-URL header' });
832
834
  return;
833
835
  }
836
+ // Hoisted so the catch handler below can detach it on early
837
+ // failures (e.g. fetch threw before the success-path detach
838
+ // could run).
839
+ let onClientClose = null;
834
840
  try {
835
841
  const fetchInit = {
836
842
  method: req.method,
@@ -940,46 +946,148 @@ async function main() {
940
946
  // Buffer extends Uint8Array which is a valid fetch body at runtime.
941
947
  fetchInit.body = rawBody;
942
948
  }
949
+ // Propagate client disconnect to the upstream request so that
950
+ // long-lived streams (LLM SSE completions) are torn down promptly
951
+ // when the SW or the page aborts. Listen on `res.on('close')` —
952
+ // not `req.on('close')` — because Node fires `req` close as soon
953
+ // as the readable side of the request is consumed (right after
954
+ // express.json() parses the body), which would abort the upstream
955
+ // fetch before it could even start. `res` close only fires when
956
+ // the response is sent OR the connection is killed mid-stream;
957
+ // in the first case the abort is harmless (the fetch already
958
+ // settled), in the second it's exactly what we want. Guard with
959
+ // `res.writableEnded` to be safe.
960
+ const abortController = new AbortController();
961
+ onClientClose = () => {
962
+ if (!res.writableEnded)
963
+ abortController.abort();
964
+ };
965
+ res.on('close', onClientClose);
966
+ fetchInit.signal = abortController.signal;
943
967
  const upstream = await fetch(targetUrl, fetchInit);
944
968
  // Forward status, prevent browser caching of proxy responses
945
969
  res.status(upstream.status);
946
970
  res.setHeader('Cache-Control', 'no-store, no-cache');
947
971
  // Forward response headers (strip www-authenticate to prevent
948
972
  // the browser from showing a native Basic Auth dialog — isomorphic-git
949
- // handles 401s through its own onAuth callback)
950
- // Forbidden-header transport: browser fetch() strips Set-Cookie from
951
- // responses. Collect all Set-Cookie values and encode as JSON in a
952
- // transport header the browser can read.
973
+ // handles 401s through its own onAuth callback). Drop Content-Length
974
+ // so the response can be chunk-encoded transparently.
953
975
  const setCookieValues = upstream.headers.getSetCookie();
954
976
  upstream.headers.forEach((v, k) => {
955
977
  const lower = k.toLowerCase();
956
978
  if (lower !== 'transfer-encoding' &&
957
979
  lower !== 'content-encoding' &&
980
+ lower !== 'content-length' &&
958
981
  lower !== 'www-authenticate' &&
959
982
  lower !== 'set-cookie' &&
960
983
  !lower.startsWith('x-proxy-')) {
961
- // Scrub real secret values from response headers
984
+ // Scrub real secret values from response headers (one-shot,
985
+ // headers are always small so per-chunk semantics don't apply).
962
986
  res.setHeader(k, secretProxy.scrubResponse(v));
963
987
  }
964
988
  });
965
989
  if (setCookieValues.length > 0) {
966
990
  res.setHeader('X-Proxy-Set-Cookie', secretProxy.scrubResponse(JSON.stringify(setCookieValues)));
967
991
  }
968
- // Send body scrub real secret values from response body (text-only)
969
- const body = await upstream.arrayBuffer();
970
- let buffer = Buffer.from(body);
971
- if (secretProxy.hasSecrets()) {
972
- const ct = (upstream.headers.get('content-type') ?? '').toLowerCase();
973
- const isText = ct.startsWith('text/') || ct.startsWith('application/json') || ct.includes('charset=');
974
- if (isText) {
975
- const scrubbed = secretProxy.scrubResponse(buffer.toString('utf-8'));
976
- buffer = Buffer.from(scrubbed, 'utf-8');
977
- }
992
+ // Stream the upstream body straight through to the client so that
993
+ // LLM SSE completions reach the browser token-by-token instead of
994
+ // arriving in one giant burst at the end. Per-chunk secret-scrub
995
+ // runs on text responses; secrets that span a chunk boundary slip
996
+ // through unscrubbed (documented limitation — the scrub primitive
997
+ // is best-effort on streamed bodies).
998
+ if (!upstream.body) {
999
+ res.end();
1000
+ if (onClientClose)
1001
+ res.off('close', onClientClose);
1002
+ return;
978
1003
  }
979
- res.setHeader('Content-Length', buffer.length);
980
- res.end(buffer);
1004
+ const ct = (upstream.headers.get('content-type') ?? '').toLowerCase();
1005
+ const isText = ct.startsWith('text/') ||
1006
+ ct.startsWith('application/json') ||
1007
+ ct.includes('charset=') ||
1008
+ ct.includes('event-stream');
1009
+ const upstreamStream = Readable.fromWeb(upstream.body);
1010
+ // Buffer-aware UTF-8 scrubber. Naive `Buffer.from(chunk).toString('utf-8')`
1011
+ // corrupts multi-byte codepoints whenever a sequence straddles a chunk
1012
+ // boundary — Node replaces the partial bytes with U+FFFD, which is fatal
1013
+ // for any non-ASCII model output (CJK, emoji, even some accented Latin).
1014
+ // `StringDecoder` keeps the trailing partial bytes in a private buffer
1015
+ // and prepends them to the next chunk, guaranteeing valid UTF-8 every
1016
+ // call. The flush() in `flush(cb)` releases any tail bytes (replacing
1017
+ // truly invalid trailing bytes with U+FFFD, same as before but only at
1018
+ // EOF where it can't span a real codepoint).
1019
+ const utf8Decoder = new StringDecoder('utf8');
1020
+ const scrubChunk = new Transform({
1021
+ transform(chunk, _enc, cb) {
1022
+ if (!isText || !secretProxy.hasSecrets()) {
1023
+ cb(null, chunk);
1024
+ return;
1025
+ }
1026
+ try {
1027
+ const decoded = utf8Decoder.write(chunk);
1028
+ if (decoded.length === 0) {
1029
+ // All bytes were buffered as a partial codepoint — no output yet.
1030
+ cb(null, Buffer.alloc(0));
1031
+ return;
1032
+ }
1033
+ const scrubbed = secretProxy.scrubResponse(decoded);
1034
+ cb(null, Buffer.from(scrubbed, 'utf-8'));
1035
+ }
1036
+ catch (err) {
1037
+ cb(err);
1038
+ }
1039
+ },
1040
+ flush(cb) {
1041
+ if (!isText || !secretProxy.hasSecrets()) {
1042
+ cb();
1043
+ return;
1044
+ }
1045
+ try {
1046
+ const tail = utf8Decoder.end();
1047
+ if (tail.length === 0) {
1048
+ cb();
1049
+ return;
1050
+ }
1051
+ const scrubbed = secretProxy.scrubResponse(tail);
1052
+ cb(null, Buffer.from(scrubbed, 'utf-8'));
1053
+ }
1054
+ catch (err) {
1055
+ cb(err);
1056
+ }
1057
+ },
1058
+ });
1059
+ const cleanup = () => {
1060
+ if (onClientClose) {
1061
+ res.off('close', onClientClose);
1062
+ onClientClose = null;
1063
+ }
1064
+ };
1065
+ upstreamStream.on('error', (err) => {
1066
+ cleanup();
1067
+ if (!res.headersSent) {
1068
+ res.setHeader('X-Proxy-Error', '1');
1069
+ res
1070
+ .status(502)
1071
+ .json({ error: `Proxy stream failed: ${err instanceof Error ? err.message : err}` });
1072
+ }
1073
+ else {
1074
+ res.destroy(err);
1075
+ }
1076
+ });
1077
+ // Belt-and-braces cleanup: 'finish' fires once the response is fully
1078
+ // flushed; 'close' fires regardless of how the response ended (success,
1079
+ // abort, or pipe error). Either way we want the abort listener gone.
1080
+ res.on('finish', cleanup);
1081
+ res.on('close', cleanup);
1082
+ upstreamStream.pipe(scrubChunk).pipe(res);
981
1083
  }
982
1084
  catch (err) {
1085
+ // Best-effort cleanup so an early failure (e.g. fetch threw) doesn't
1086
+ // leave the close listener attached to the response object.
1087
+ if (onClientClose) {
1088
+ res.off('close', onClientClose);
1089
+ onClientClose = null;
1090
+ }
983
1091
  const message = err instanceof Error ? err.message : String(err);
984
1092
  res.setHeader('X-Proxy-Error', '1');
985
1093
  res.status(502).json({ error: `Proxy fetch failed: ${message}` });
@@ -1029,7 +1137,17 @@ async function main() {
1029
1137
  else {
1030
1138
  // Production mode: serve built static files
1031
1139
  const uiDir = resolve(__dirname, '..', 'ui');
1032
- app.use(express.static(uiDir));
1140
+ app.use(express.static(uiDir, {
1141
+ setHeaders: (res, path) => {
1142
+ // Service workers must declare a maximum scope; without
1143
+ // `Service-Worker-Allowed: /`, the browser refuses to register
1144
+ // a root-scoped SW served from `/llm-proxy-sw.js`.
1145
+ if (path.endsWith('llm-proxy-sw.js')) {
1146
+ res.setHeader('Service-Worker-Allowed', '/');
1147
+ res.setHeader('Cache-Control', 'no-store');
1148
+ }
1149
+ },
1150
+ }));
1033
1151
  // SPA fallback — serve index.html for all non-file routes
1034
1152
  app.get('/{*path}', (_req, res) => {
1035
1153
  res.sendFile(join(uiDir, 'index.html'));
@@ -9,7 +9,6 @@ interface ReleaseManifest {
9
9
  npmPackageTarball: string;
10
10
  }
11
11
  export declare function sanitizeArtifactName(value: string): string;
12
- export declare function assertMatchingVersions(packageVersion: string, extensionVersion: string): void;
13
12
  export declare function collectZipEntries(rootDir: string): ZipEntry[];
14
13
  export declare function createDeterministicZip(entries: readonly ZipEntry[]): Buffer;
15
14
  export declare function parseNpmPackFilename(output: string): string;
@@ -29,11 +29,6 @@ export function sanitizeArtifactName(value) {
29
29
  .replace(/-+/g, '-')
30
30
  .replace(/^-|-$/g, '');
31
31
  }
32
- export function assertMatchingVersions(packageVersion, extensionVersion) {
33
- if (packageVersion !== extensionVersion) {
34
- throw new Error(`package.json version (${packageVersion}) must match manifest.json version (${extensionVersion}) before packaging release artifacts.`);
35
- }
36
- }
37
32
  export function collectZipEntries(rootDir) {
38
33
  const entries = [];
39
34
  const walk = (currentDir) => {
@@ -198,11 +193,9 @@ function writeReleaseManifest(manifest) {
198
193
  }
199
194
  export function packageReleaseArtifacts() {
200
195
  const packageJson = readJsonFile(resolve(PROJECT_ROOT, 'package.json'));
201
- const extensionManifest = readJsonFile(resolve(PROJECT_ROOT, 'packages/chrome-extension/manifest.json'));
202
- assertMatchingVersions(packageJson.version, extensionManifest.version);
203
196
  rmSync(RELEASE_DIR, { recursive: true, force: true });
204
197
  mkdirSync(RELEASE_DIR, { recursive: true });
205
- const extensionArchive = createExtensionArchive(extensionManifest);
198
+ const extensionArchive = createExtensionArchive(packageJson);
206
199
  const npmPackageTarball = createNpmPackageTarball();
207
200
  const manifest = {
208
201
  version: packageJson.version,
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,s as r,t as i}from"./simple-options-CRMUB9za.js";import{d as a,l as o,u as s}from"./index-n7dM8Ny6.js";import{t as c}from"./headers-DkHU-pcw.js";import{t as l}from"./sanitize-unicode-BD2XKRoV.js";import{i as u,n as ee,t as d}from"./github-copilot-headers-B6Fvsk-Y.js";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var h=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},g=class extends Error{},_=class e extends g{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ne({message:r,cause:h(n)});let a=n,o=a?.error?.type;return t===400?new ie(t,a,r,i,o):t===401?new ae(t,a,r,i,o):t===403?new oe(t,a,r,i,o):t===404?new se(t,a,r,i,o):t===409?new ce(t,a,r,i,o):t===422?new le(t,a,r,i,o):t===429?new ue(t,a,r,i,o):t>=500?new de(t,a,r,i,o):new e(t,a,r,i,o)}},v=class extends _{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ne=class extends _{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},re=class extends ne{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ie=class extends _{},ae=class extends _{},oe=class extends _{},se=class extends _{},ce=class extends _{},le=class extends _{},ue=class extends _{},de=class extends _{},fe=/^[a-z][a-z0-9+.-]*:/i,pe=e=>fe.test(e),me=e=>(me=Array.isArray,me(e)),he=me;function ge(e){return typeof e==`object`?e??{}:{}}function _e(e){if(!e)return!0;for(let t in e)return!1;return!0}function ve(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},be=e=>{try{return JSON.parse(e)}catch{return}},xe=e=>new Promise(t=>setTimeout(t,e)),y=`0.91.1`,Se=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Ce(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var we=()=>{let e=Ce();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(Deno.build.os),"X-Stainless-Arch":Ee(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":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ee(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Te();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Te(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var Ee=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,De=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Oe,ke=()=>Oe??=we();function Ae(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function je(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Me(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return je({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ne(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Fe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Ie(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Le(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Re;function ze(e){let t;return(Re??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var b,x,He=class{constructor(){b.set(this,void 0),x.set(this,void 0),f(this,b,new Uint8Array,`f`),f(this,x,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?ze(e):e;f(this,b,Le([p(this,b,`f`),t]),`f`);let n=[],r;for(;(r=Ue(p(this,b,`f`),p(this,x,`f`)))!=null;){if(r.carriage&&p(this,x,`f`)==null){f(this,x,r.index,`f`);continue}if(p(this,x,`f`)!=null&&(r.index!==p(this,x,`f`)+1||r.carriage)){n.push(Ve(p(this,b,`f`).subarray(0,p(this,x,`f`)-1))),f(this,b,p(this,b,`f`).subarray(p(this,x,`f`)),`f`),f(this,x,null,`f`);continue}let e=p(this,x,`f`)===null?r.preceding:r.preceding-1,t=Ve(p(this,b,`f`).subarray(0,e));n.push(t),f(this,b,p(this,b,`f`).subarray(r.index),`f`),f(this,x,null,`f`)}return n}flush(){return p(this,b,`f`).length?this.decode(`
1
+ import{a as e,c as t,i as n,n as r,o as i,t as a}from"./simple-options-CDIijiMb.js";import{t as o}from"./headers-qDMOQQGF.js";import{f as s,m as c,p as l}from"./index-hy37TrIH.js";import{i as u,n as ee,t as d}from"./github-copilot-headers-DGaOrqaW.js";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var h=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},g=class extends Error{},_=class e extends g{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ne({message:r,cause:h(n)});let a=n,o=a?.error?.type;return t===400?new ie(t,a,r,i,o):t===401?new ae(t,a,r,i,o):t===403?new oe(t,a,r,i,o):t===404?new se(t,a,r,i,o):t===409?new ce(t,a,r,i,o):t===422?new le(t,a,r,i,o):t===429?new ue(t,a,r,i,o):t>=500?new de(t,a,r,i,o):new e(t,a,r,i,o)}},v=class extends _{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ne=class extends _{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},re=class extends ne{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ie=class extends _{},ae=class extends _{},oe=class extends _{},se=class extends _{},ce=class extends _{},le=class extends _{},ue=class extends _{},de=class extends _{},fe=/^[a-z][a-z0-9+.-]*:/i,pe=e=>fe.test(e),me=e=>(me=Array.isArray,me(e)),he=me;function ge(e){return typeof e==`object`?e??{}:{}}function _e(e){if(!e)return!0;for(let t in e)return!1;return!0}function ve(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},be=e=>{try{return JSON.parse(e)}catch{return}},xe=e=>new Promise(t=>setTimeout(t,e)),y=`0.91.1`,Se=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Ce(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var we=()=>{let e=Ce();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(Deno.build.os),"X-Stainless-Arch":Ee(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":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ee(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Te();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Te(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var Ee=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,De=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Oe,ke=()=>Oe??=we();function Ae(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function je(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Me(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return je({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ne(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Fe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Ie(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Le(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Re;function ze(e){let t;return(Re??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var b,x,He=class{constructor(){b.set(this,void 0),x.set(this,void 0),f(this,b,new Uint8Array,`f`),f(this,x,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?ze(e):e;f(this,b,Le([p(this,b,`f`),t]),`f`);let n=[],r;for(;(r=Ue(p(this,b,`f`),p(this,x,`f`)))!=null;){if(r.carriage&&p(this,x,`f`)==null){f(this,x,r.index,`f`);continue}if(p(this,x,`f`)!=null&&(r.index!==p(this,x,`f`)+1||r.carriage)){n.push(Ve(p(this,b,`f`).subarray(0,p(this,x,`f`)-1))),f(this,b,p(this,b,`f`).subarray(p(this,x,`f`)),`f`),f(this,x,null,`f`);continue}let e=p(this,x,`f`)===null?r.preceding:r.preceding-1,t=Ve(p(this,b,`f`).subarray(0,e));n.push(t),f(this,b,p(this,b,`f`).subarray(r.index),`f`),f(this,x,null,`f`)}return n}flush(){return p(this,b,`f`).length?this.decode(`
2
2
  `):[]}};b=new WeakMap,x=new WeakMap,He.NEWLINE_CHARS=new Set([`
3
3
  `,`\r`]),He.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ue(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function We(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},Ke=(e,t,n)=>{if(e){if(ve(Ge,e))return e;S(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function qe(){}function Je(e,t,n){return!t||Ge[e]>Ge[n]?qe:t[e].bind(t)}var Ye={error:qe,warn:qe,info:qe,debug:qe},Xe=new WeakMap;function S(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ye;let r=Xe.get(t);if(r&&r[0]===n)return r[1];let i={error:Je(`error`,t,n),warn:Je(`warn`,t,n),info:Je(`info`,t,n),debug:Je(`debug`,t,n)};return Xe.set(t,[n,i]),i}var C=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Ze,Qe=class e{constructor(e,t,n){this.iterator=e,Ze.set(this,void 0),this.controller=t,f(this,Ze,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?S(r):console;async function*o(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of $e(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=be(e.data)??e.data,r=n?.error?.type;throw new _(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new He,n=Ne(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Ze=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,p(this,Ze,`f`)),new e(()=>i(n),this.controller,p(this,Ze,`f`))]}toReadableStream(){let e=this,t;return je({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=ze(JSON.stringify(n)+`
4
4
  `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*$e(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new g(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new g(`Attempted to iterate over a response with no body`);let n=new tt,r=new He,i=Ne(e.body);for await(let e of et(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*et(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?ze(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=We(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var tt=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 e={event:this.event,data:this.data.join(`
@@ -32,8 +32,8 @@ If you understand the risks and have appropriate mitigations in place,
32
32
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
33
33
 
34
34
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
35
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??br.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Ke(i.logLevel,`ClientOptions.logLevel`,this)??Ke(vr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Ae(),f(this,xr,Fe,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return O([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return O([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return O([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ie(e)}getUserAgent(){return`${this.constructor.name}/JS ${y}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,yr,`m`,Sr).call(this)&&n||this.baseURL,i=pe(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_e(a)||!_e(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ot(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new v;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(h),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new v;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new re:new ne({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Pe(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>h(e).message),o=be(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new lt(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await xe(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=O([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ke(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=O([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Me(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,xr,`f`).call(this,{body:e,headers:n})}};br=Q,xr=new WeakMap,yr=new WeakSet,Sr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=br,Q.HUMAN_PROMPT=Cr,Q.AI_PROMPT=wr,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=g,Q.APIError=_,Q.APIConnectionError=ne,Q.APIConnectionTimeoutError=re,Q.APIUserAbortError=v,Q.NotFoundError=se,Q.ConflictError=ce,Q.RateLimitError=ue,Q.BadRequestError=ie,Q.AuthenticationError=ae,Q.InternalServerError=de,Q.PermissionDeniedError=oe,Q.UnprocessableEntityError=le,Q.toFile=St;var $=class extends Q{constructor(){super(...arguments),this.completions=new Bn(this),this.messages=new mr(this),this.models=new _r(this),this.beta=new K(this)}};$.Completions=Bn,$.Messages=mr,$.Models=_r,$.Beta=K;function Tr(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function Er(e,t){let n=Tr(t);if(n===`none`)return{retention:n};let r=n===`long`&&Pr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:n,cacheControl:{type:`ephemeral`,...r&&{ttl:r}}}}var Dr=`2.1.75`,Or=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),kr=e=>Or.get(e.toLowerCase())??e,Ar=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function jr(e){if(!e.some(e=>e.type===`image`))return l(e.map(e=>e.text).join(`
36
- `));let t=e.map(e=>e.type===`text`?{type:`text`,text:l(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}});return t.some(e=>e.type===`text`)||t.unshift({type:`text`,text:`(see attached image)`}),t}var Mr=`fine-grained-tool-streaming-2025-05-14`,Nr=`interleaved-thinking-2025-05-14`;function Pr(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function Fr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}var Ir=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Lr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
35
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??br.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Ke(i.logLevel,`ClientOptions.logLevel`,this)??Ke(vr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Ae(),f(this,xr,Fe,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return O([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return O([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return O([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ie(e)}getUserAgent(){return`${this.constructor.name}/JS ${y}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,yr,`m`,Sr).call(this)&&n||this.baseURL,i=pe(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_e(a)||!_e(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ot(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new v;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(h),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new v;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new re:new ne({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Pe(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>h(e).message),o=be(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new lt(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await xe(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=O([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ke(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=O([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Me(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,xr,`f`).call(this,{body:e,headers:n})}};br=Q,xr=new WeakMap,yr=new WeakSet,Sr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=br,Q.HUMAN_PROMPT=Cr,Q.AI_PROMPT=wr,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=g,Q.APIError=_,Q.APIConnectionError=ne,Q.APIConnectionTimeoutError=re,Q.APIUserAbortError=v,Q.NotFoundError=se,Q.ConflictError=ce,Q.RateLimitError=ue,Q.BadRequestError=ie,Q.AuthenticationError=ae,Q.InternalServerError=de,Q.PermissionDeniedError=oe,Q.UnprocessableEntityError=le,Q.toFile=St;var $=class extends Q{constructor(){super(...arguments),this.completions=new Bn(this),this.messages=new mr(this),this.models=new _r(this),this.beta=new K(this)}};$.Completions=Bn,$.Messages=mr,$.Models=_r,$.Beta=K;function Tr(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function Er(e,t){let n=Tr(t);if(n===`none`)return{retention:n};let r=n===`long`&&Pr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:n,cacheControl:{type:`ephemeral`,...r&&{ttl:r}}}}var Dr=`2.1.75`,Or=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),kr=e=>Or.get(e.toLowerCase())??e,Ar=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function jr(t){if(!t.some(e=>e.type===`image`))return e(t.map(e=>e.text).join(`
36
+ `));let n=t.map(t=>t.type===`text`?{type:`text`,text:e(t.text)}:{type:`image`,source:{type:`base64`,media_type:t.mimeType,data:t.data}});return n.some(e=>e.type===`text`)||n.unshift({type:`text`,text:`(see attached image)`}),n}var Mr=`fine-grained-tool-streaming-2025-05-14`,Nr=`interleaved-thinking-2025-05-14`;function Pr(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function Fr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}var Ir=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Lr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
37
37
  `),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Rr(e,t){if(e===``)return Lr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function zr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
38
38
  `);return t===-1?n:n===-1?t:Math.min(t,n)}function Br(e){let t=zr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
39
- `&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Vr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Br(a);for(;s;){a=s.rest;let e=Rr(s.line,i);e&&(yield e),s=Br(a)}}a+=r.decode();let e=Br(a);for(;e;){a=e.rest;let t=Rr(e.line,i);t&&(yield t),e=Br(a)}if(a.length>0){let e=Rr(a,i);e&&(yield e)}let o=Lr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Hr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,r=!1;for await(let i of Vr(e.body,t)){if(i.event===`error`)throw Error(i.data);if(Ir.has(i.event??``))try{let e=o(i.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(r=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${i.event}: ${t}; data=${i.data}; raw=${i.raw.join(`\\n`)}`)}}if(n&&!r)throw Error(`Anthropic stream ended before message_stop`)}var Ur=(t,n,i)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l,u;if(i?.client)l=i.client,u=!1;else{let e=i?.apiKey??a(t.provider)??``,r;if(t.provider===`github-copilot`){let e=ee(n.messages);r=d({messages:n.messages,hasImages:e})}let o=Jr(t,e,i?.interleavedThinking??!0,Qr(t,n),i?.headers,r);l=o.client,u=o.isOAuthToken}let f=Yr(t,n,u,i),p=await i?.onPayload?.(f,t);p!==void 0&&(f=p);let te={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},m=await l.messages.create({...f,stream:!0},te).asResponse();await i?.onResponse?.({status:m.status,headers:c(m.headers)},t),o.push({type:`start`,partial:e});let h=e.content;for await(let a of Hr(m,i?.signal))if(a.type===`message_start`)e.responseId=a.message.id,e.usage.input=a.message.usage.input_tokens||0,e.usage.output=a.message.usage.output_tokens||0,e.usage.cacheRead=a.message.usage.cache_read_input_tokens||0,e.usage.cacheWrite=a.message.usage.cache_creation_input_tokens||0,e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,r(t,e.usage);else if(a.type===`content_block_start`){if(a.content_block.type===`text`){let t={type:`text`,text:``,index:a.index};e.content.push(t),o.push({type:`text_start`,contentIndex:e.content.length-1,partial:e})}else if(a.content_block.type===`thinking`){let t={type:`thinking`,thinking:``,thinkingSignature:``,index:a.index};e.content.push(t),o.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(a.content_block.type===`redacted_thinking`){let t={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:a.content_block.data,redacted:!0,index:a.index};e.content.push(t),o.push({type:`thinking_start`,contentIndex:e.content.length-1,partial:e})}else if(a.content_block.type===`tool_use`){let t={type:`toolCall`,id:a.content_block.id,name:u?Ar(a.content_block.name,n.tools):a.content_block.name,arguments:a.content_block.input??{},partialJson:``,index:a.index};e.content.push(t),o.push({type:`toolcall_start`,contentIndex:e.content.length-1,partial:e})}}else if(a.type===`content_block_delta`){if(a.delta.type===`text_delta`){let t=h.findIndex(e=>e.index===a.index),n=h[t];n&&n.type===`text`&&(n.text+=a.delta.text,o.push({type:`text_delta`,contentIndex:t,delta:a.delta.text,partial:e}))}else if(a.delta.type===`thinking_delta`){let t=h.findIndex(e=>e.index===a.index),n=h[t];n&&n.type===`thinking`&&(n.thinking+=a.delta.thinking,o.push({type:`thinking_delta`,contentIndex:t,delta:a.delta.thinking,partial:e}))}else if(a.delta.type===`input_json_delta`){let t=h.findIndex(e=>e.index===a.index),n=h[t];n&&n.type===`toolCall`&&(n.partialJson+=a.delta.partial_json,n.arguments=s(n.partialJson),o.push({type:`toolcall_delta`,contentIndex:t,delta:a.delta.partial_json,partial:e}))}else if(a.delta.type===`signature_delta`){let e=h[h.findIndex(e=>e.index===a.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=a.delta.signature)}}else if(a.type===`content_block_stop`){let t=h.findIndex(e=>e.index===a.index),n=h[t];n&&(delete n.index,n.type===`text`?o.push({type:`text_end`,contentIndex:t,content:n.text,partial:e}):n.type===`thinking`?o.push({type:`thinking_end`,contentIndex:t,content:n.thinking,partial:e}):n.type===`toolCall`&&(n.arguments=s(n.partialJson),delete n.partialJson,o.push({type:`toolcall_end`,contentIndex:t,toolCall:n,partial:e})))}else a.type===`message_delta`&&(a.delta.stop_reason&&(e.stopReason=ei(a.delta.stop_reason)),a.usage.input_tokens!=null&&(e.usage.input=a.usage.input_tokens),a.usage.output_tokens!=null&&(e.usage.output=a.usage.output_tokens),a.usage.cache_read_input_tokens!=null&&(e.usage.cacheRead=a.usage.cache_read_input_tokens),a.usage.cache_creation_input_tokens!=null&&(e.usage.cacheWrite=a.usage.cache_creation_input_tokens),e.usage.totalTokens=e.usage.input+e.usage.output+e.usage.cacheRead+e.usage.cacheWrite,r(t,e.usage));if(i?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=t instanceof Error?t.message:JSON.stringify(t),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o};function Wr(e){return e.includes(`opus-4-6`)||e.includes(`opus-4.6`)||e.includes(`opus-4-7`)||e.includes(`opus-4.7`)||e.includes(`sonnet-4-6`)||e.includes(`sonnet-4.6`)}function Gr(e,t){switch(e){case`minimal`:return`low`;case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;case`xhigh`:return t.includes(`opus-4-6`)||t.includes(`opus-4.6`)?`max`:t.includes(`opus-4-7`)||t.includes(`opus-4.7`)?`xhigh`:`high`;default:return`high`}}var Kr=(e,t,r)=>{let o=r?.apiKey||a(e.provider);if(!o)throw Error(`No API key for provider: ${e.provider}`);let s=n(e,r,o);if(!r?.reasoning)return Ur(e,t,{...s,thinkingEnabled:!1});if(Wr(e.id)){let n=Gr(r.reasoning,e.id);return Ur(e,t,{...s,thinkingEnabled:!0,effort:n})}let c=i(s.maxTokens||0,e.maxTokens,r.reasoning,r.thinkingBudgets);return Ur(e,t,{...s,maxTokens:c.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:c.thinkingBudget})};function qr(e){return e.includes(`sk-ant-oat`)}function Jr(e,t,n,r,i,a){let o=n&&!Wr(e.id),s=[];return r&&s.push(Mr),o&&s.push(Nr),e.provider===`cloudflare-ai-gateway`?{client:new $({apiKey:null,authToken:null,baseURL:u(e),dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"cf-aig-authorization":`Bearer ${t}`,"x-api-key":null,Authorization:null,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}:e.provider===`github-copilot`?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1}:qr(t)?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...s].join(`,`),"user-agent":`claude-cli/${Dr}`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0}:{client:new $({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}}function Yr(e,t,n,r){let{cacheControl:i}=Er(e,r?.cacheRetention),a={model:e.id,messages:Zr(t.messages,e,n,i),max_tokens:r?.maxTokens||e.maxTokens/3|0,stream:!0};if(n?(a.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...i?{cache_control:i}:{}}],t.systemPrompt&&a.system.push({type:`text`,text:l(t.systemPrompt),...i?{cache_control:i}:{}})):t.systemPrompt&&(a.system=[{type:`text`,text:l(t.systemPrompt),...i?{cache_control:i}:{}}]),r?.temperature!==void 0&&!r?.thinkingEnabled&&(a.temperature=r.temperature),t.tools&&t.tools.length>0&&(a.tools=$r(t.tools,n,Pr(e).supportsEagerToolInputStreaming,i)),e.reasoning)if(r?.thinkingEnabled){let t=r.thinkingDisplay??`summarized`;Wr(e.id)?(a.thinking={type:`adaptive`,display:t},r.effort&&(a.output_config=(r.effort,{effort:r.effort}))):a.thinking={type:`enabled`,budget_tokens:r.thinkingBudgetTokens||1024,display:t}}else r?.thinkingEnabled===!1&&(a.thinking={type:`disabled`});if(r?.metadata){let e=r.metadata.user_id;typeof e==`string`&&(a.metadata={user_id:e})}return r?.toolChoice&&(typeof r.toolChoice==`string`?a.tool_choice={type:r.toolChoice}:a.tool_choice=r.toolChoice),a}function Xr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Zr(e,n,r,i){let a=[],o=t(e,n,Xr);for(let e=0;e<o.length;e++){let t=o[e];if(t.role===`user`)if(typeof t.content==`string`)t.content.trim().length>0&&a.push({role:`user`,content:l(t.content)});else{let e=t.content.map(e=>e.type===`text`?{type:`text`,text:l(e.text)}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}}).filter(e=>e.type===`text`?e.text.trim().length>0:!0);if(e.length===0)continue;a.push({role:`user`,content:e})}else if(t.role===`assistant`){let e=[];for(let n of t.content)if(n.type===`text`){if(n.text.trim().length===0)continue;e.push({type:`text`,text:l(n.text)})}else if(n.type===`thinking`){if(n.redacted){e.push({type:`redacted_thinking`,data:n.thinkingSignature});continue}if(n.thinking.trim().length===0)continue;!n.thinkingSignature||n.thinkingSignature.trim().length===0?e.push({type:`text`,text:l(n.thinking)}):e.push({type:`thinking`,thinking:l(n.thinking),signature:n.thinkingSignature})}else n.type===`toolCall`&&e.push({type:`tool_use`,id:n.id,name:r?kr(n.name):n.name,input:n.arguments??{}});if(e.length===0)continue;a.push({role:`assistant`,content:e})}else if(t.role===`toolResult`){let n=[];n.push({type:`tool_result`,tool_use_id:t.toolCallId,content:jr(t.content),is_error:t.isError});let r=e+1;for(;r<o.length&&o[r].role===`toolResult`;){let e=o[r];n.push({type:`tool_result`,tool_use_id:e.toolCallId,content:jr(e.content),is_error:e.isError}),r++}e=r-1,a.push({role:`user`,content:n})}}if(i&&a.length>0){let e=a[a.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=i)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:i}])}return a}function Qr(e,t){return!!t.tools?.length&&!Pr(e).supportsEagerToolInputStreaming}function $r(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?kr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function ei(e){switch(e){case`end_turn`:return`stop`;case`max_tokens`:return`length`;case`tool_use`:return`toolUse`;case`refusal`:return`error`;case`pause_turn`:return`stop`;case`stop_sequence`:return`stop`;case`sensitive`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{Ur as streamAnthropic,Kr as streamSimpleAnthropic};
39
+ `&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Vr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Br(a);for(;s;){a=s.rest;let e=Rr(s.line,i);e&&(yield e),s=Br(a)}}a+=r.decode();let e=Br(a);for(;e;){a=e.rest;let t=Rr(e.line,i);t&&(yield t),e=Br(a)}if(a.length>0){let e=Rr(a,i);e&&(yield e)}let o=Lr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Hr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,r=!1;for await(let i of Vr(e.body,t)){if(i.event===`error`)throw Error(i.data);if(Ir.has(i.event??``))try{let e=s(i.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(r=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${i.event}: ${t}; data=${i.data}; raw=${i.raw.join(`\\n`)}`)}}if(n&&!r)throw Error(`Anthropic stream ended before message_stop`)}var Ur=(e,n,r)=>{let a=new i;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s,u;if(r?.client)s=r.client,u=!1;else{let t=r?.apiKey??c(e.provider)??``,i;if(e.provider===`github-copilot`){let e=ee(n.messages);i=d({messages:n.messages,hasImages:e})}let a=Jr(e,t,r?.interleavedThinking??!0,Qr(e,n),r?.headers,i);s=a.client,u=a.isOAuthToken}let f=Yr(e,n,u,r),p=await r?.onPayload?.(f,e);p!==void 0&&(f=p);let te={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},...r?.maxRetries===void 0?{}:{maxRetries:r.maxRetries}},m=await s.messages.create({...f,stream:!0},te).asResponse();await r?.onResponse?.({status:m.status,headers:o(m.headers)},e),a.push({type:`start`,partial:i});let h=i.content;for await(let o of Hr(m,r?.signal))if(o.type===`message_start`)i.responseId=o.message.id,i.usage.input=o.message.usage.input_tokens||0,i.usage.output=o.message.usage.output_tokens||0,i.usage.cacheRead=o.message.usage.cache_read_input_tokens||0,i.usage.cacheWrite=o.message.usage.cache_creation_input_tokens||0,i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,t(e,i.usage);else if(o.type===`content_block_start`){if(o.content_block.type===`text`){let e={type:`text`,text:``,index:o.index};i.content.push(e),a.push({type:`text_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`thinking`){let e={type:`thinking`,thinking:``,thinkingSignature:``,index:o.index};i.content.push(e),a.push({type:`thinking_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`redacted_thinking`){let e={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:o.content_block.data,redacted:!0,index:o.index};i.content.push(e),a.push({type:`thinking_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`tool_use`){let e={type:`toolCall`,id:o.content_block.id,name:u?Ar(o.content_block.name,n.tools):o.content_block.name,arguments:o.content_block.input??{},partialJson:``,index:o.index};i.content.push(e),a.push({type:`toolcall_start`,contentIndex:i.content.length-1,partial:i})}}else if(o.type===`content_block_delta`){if(o.delta.type===`text_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`text`&&(t.text+=o.delta.text,a.push({type:`text_delta`,contentIndex:e,delta:o.delta.text,partial:i}))}else if(o.delta.type===`thinking_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`thinking`&&(t.thinking+=o.delta.thinking,a.push({type:`thinking_delta`,contentIndex:e,delta:o.delta.thinking,partial:i}))}else if(o.delta.type===`input_json_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`toolCall`&&(t.partialJson+=o.delta.partial_json,t.arguments=l(t.partialJson),a.push({type:`toolcall_delta`,contentIndex:e,delta:o.delta.partial_json,partial:i}))}else if(o.delta.type===`signature_delta`){let e=h[h.findIndex(e=>e.index===o.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=o.delta.signature)}}else if(o.type===`content_block_stop`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&(delete t.index,t.type===`text`?a.push({type:`text_end`,contentIndex:e,content:t.text,partial:i}):t.type===`thinking`?a.push({type:`thinking_end`,contentIndex:e,content:t.thinking,partial:i}):t.type===`toolCall`&&(t.arguments=l(t.partialJson),delete t.partialJson,a.push({type:`toolcall_end`,contentIndex:e,toolCall:t,partial:i})))}else o.type===`message_delta`&&(o.delta.stop_reason&&(i.stopReason=ei(o.delta.stop_reason)),o.usage.input_tokens!=null&&(i.usage.input=o.usage.input_tokens),o.usage.output_tokens!=null&&(i.usage.output=o.usage.output_tokens),o.usage.cache_read_input_tokens!=null&&(i.usage.cacheRead=o.usage.cache_read_input_tokens),o.usage.cache_creation_input_tokens!=null&&(i.usage.cacheWrite=o.usage.cache_creation_input_tokens),i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,t(e,i.usage));if(r?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end()}catch(e){for(let e of i.content)delete e.index,delete e.partialJson;i.stopReason=r?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),a.push({type:`error`,reason:i.stopReason,error:i}),a.end()}})(),a};function Wr(e){return e.includes(`opus-4-6`)||e.includes(`opus-4.6`)||e.includes(`opus-4-7`)||e.includes(`opus-4.7`)||e.includes(`sonnet-4-6`)||e.includes(`sonnet-4.6`)}function Gr(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}var Kr=(e,t,n)=>{let i=n?.apiKey||c(e.provider);if(!i)throw Error(`No API key for provider: ${e.provider}`);let o=r(e,n,i);if(!n?.reasoning)return Ur(e,t,{...o,thinkingEnabled:!1});if(Wr(e.id)){let r=Gr(e,n.reasoning);return Ur(e,t,{...o,thinkingEnabled:!0,effort:r})}let s=a(o.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return Ur(e,t,{...o,maxTokens:s.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:s.thinkingBudget})};function qr(e){return e.includes(`sk-ant-oat`)}function Jr(e,t,n,r,i,a){let o=n&&!Wr(e.id),s=[];return r&&s.push(Mr),o&&s.push(Nr),e.provider===`cloudflare-ai-gateway`?{client:new $({apiKey:null,authToken:null,baseURL:u(e),dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"cf-aig-authorization":`Bearer ${t}`,"x-api-key":null,Authorization:null,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}:e.provider===`github-copilot`?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1}:qr(t)?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...s].join(`,`),"user-agent":`claude-cli/${Dr}`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0}:{client:new $({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}}function Yr(t,n,r,i){let{cacheControl:a}=Er(t,i?.cacheRetention),o={model:t.id,messages:Zr(n.messages,t,r,a),max_tokens:i?.maxTokens||t.maxTokens/3|0,stream:!0};if(r?(o.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...a?{cache_control:a}:{}}],n.systemPrompt&&o.system.push({type:`text`,text:e(n.systemPrompt),...a?{cache_control:a}:{}})):n.systemPrompt&&(o.system=[{type:`text`,text:e(n.systemPrompt),...a?{cache_control:a}:{}}]),i?.temperature!==void 0&&!i?.thinkingEnabled&&(o.temperature=i.temperature),n.tools&&n.tools.length>0&&(o.tools=$r(n.tools,r,Pr(t).supportsEagerToolInputStreaming,a)),t.reasoning)if(i?.thinkingEnabled){let e=i.thinkingDisplay??`summarized`;Wr(t.id)?(o.thinking={type:`adaptive`,display:e},i.effort&&(o.output_config=(i.effort,{effort:i.effort}))):o.thinking={type:`enabled`,budget_tokens:i.thinkingBudgetTokens||1024,display:e}}else i?.thinkingEnabled===!1&&(o.thinking={type:`disabled`});if(i?.metadata){let e=i.metadata.user_id;typeof e==`string`&&(o.metadata={user_id:e})}return i?.toolChoice&&(typeof i.toolChoice==`string`?o.tool_choice={type:i.toolChoice}:o.tool_choice=i.toolChoice),o}function Xr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Zr(t,r,i,a){let o=[],s=n(t,r,Xr);for(let t=0;t<s.length;t++){let n=s[t];if(n.role===`user`)if(typeof n.content==`string`)n.content.trim().length>0&&o.push({role:`user`,content:e(n.content)});else{let t=n.content.map(t=>t.type===`text`?{type:`text`,text:e(t.text)}:{type:`image`,source:{type:`base64`,media_type:t.mimeType,data:t.data}}).filter(e=>e.type===`text`?e.text.trim().length>0:!0);if(t.length===0)continue;o.push({role:`user`,content:t})}else if(n.role===`assistant`){let t=[];for(let r of n.content)if(r.type===`text`){if(r.text.trim().length===0)continue;t.push({type:`text`,text:e(r.text)})}else if(r.type===`thinking`){if(r.redacted){t.push({type:`redacted_thinking`,data:r.thinkingSignature});continue}if(r.thinking.trim().length===0)continue;!r.thinkingSignature||r.thinkingSignature.trim().length===0?t.push({type:`text`,text:e(r.thinking)}):t.push({type:`thinking`,thinking:e(r.thinking),signature:r.thinkingSignature})}else r.type===`toolCall`&&t.push({type:`tool_use`,id:r.id,name:i?kr(r.name):r.name,input:r.arguments??{}});if(t.length===0)continue;o.push({role:`assistant`,content:t})}else if(n.role===`toolResult`){let e=[];e.push({type:`tool_result`,tool_use_id:n.toolCallId,content:jr(n.content),is_error:n.isError});let r=t+1;for(;r<s.length&&s[r].role===`toolResult`;){let t=s[r];e.push({type:`tool_result`,tool_use_id:t.toolCallId,content:jr(t.content),is_error:t.isError}),r++}t=r-1,o.push({role:`user`,content:e})}}if(a&&o.length>0){let e=o[o.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=a)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:a}])}return o}function Qr(e,t){return!!t.tools?.length&&!Pr(e).supportsEagerToolInputStreaming}function $r(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?kr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function ei(e){switch(e){case`end_turn`:return`stop`;case`max_tokens`:return`length`;case`tool_use`:return`toolUse`;case`refusal`:return`error`;case`pause_turn`:return`stop`;case`stop_sequence`:return`stop`;case`sensitive`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{Ur as streamAnthropic,Kr as streamSimpleAnthropic};
@@ -0,0 +1 @@
1
+ import{l as e,n as t,o as n}from"./simple-options-CDIijiMb.js";import{t as r}from"./headers-qDMOQQGF.js";import{t as i}from"./openai-D4NSaQIs.js";import{d as a,l as o,m as s,u as c}from"./index-hy37TrIH.js";var l=`v1`,u=new Set([`openai`,`openai-codex`,`opencode`,`azure-openai-responses`]);function d(e){let t=new Map;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let[r,i]=e.split(`=`,2);!r||!i||t.set(r.trim(),i.trim())}return t}function f(e,t){return t?.azureDeploymentName?t.azureDeploymentName:d({}.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(e.id)||e.id}var p=(e,t,i)=>{let o=new n;return(async()=>{let n=f(e,i),c={role:`assistant`,content:[],api:`azure-openai-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l=v(e,i?.apiKey||s(e.provider)||``,i),u=y(e,t,i,n),d=await i?.onPayload?.(u,e);d!==void 0&&(u=d);let f={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:p,response:m}=await l.responses.create(u,f).withResponse();if(await i?.onResponse?.({status:m.status,headers:r(m.headers)},e),o.push({type:`start`,partial:c}),await a(p,c,o,e),i?.signal?.aborted)throw Error(`Request was aborted`);if(c.stopReason===`aborted`||c.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:c.stopReason,message:c}),o.end()}catch(e){for(let e of c.content)delete e.index,delete e.partialJson;c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:c.stopReason,error:c}),o.end()}})(),o},m=(n,r,i)=>{let a=i?.apiKey||s(n.provider);if(!a)throw Error(`No API key for provider: ${n.provider}`);let o=t(n,i,a),c=i?.reasoning?e(n,i.reasoning):void 0,l=c===`off`?void 0:c;return p(n,r,{...o,reasoningEffort:l})};function h(e){let t=e.trim().replace(/\/+$/,``),n;try{n=new URL(t)}catch{throw Error(`Invalid Azure OpenAI base URL: ${e}`)}let r=n.hostname.endsWith(`.openai.azure.com`)||n.hostname.endsWith(`.cognitiveservices.azure.com`),i=n.pathname.replace(/\/+$/,``);return r&&(i===``||i===`/`||i===`/openai`)&&(n.pathname=`/openai/v1`,n.search=``),n.toString().replace(/\/+$/,``)}function g(e){return`https://${e}.openai.azure.com/openai/v1`}function _(e,t){let n=t?.azureApiVersion||{}.AZURE_OPENAI_API_VERSION||l,r=t?.azureBaseUrl?.trim()||{}.AZURE_OPENAI_BASE_URL?.trim()||void 0,i=t?.azureResourceName||{}.AZURE_OPENAI_RESOURCE_NAME,a=r;if(!a&&i&&(a=g(i)),!a&&e.baseUrl&&(a=e.baseUrl),!a)throw Error(`Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.`);return{baseUrl:h(a),apiVersion:n}}function v(e,t,n){if(!t){if(!{}.AZURE_OPENAI_API_KEY)throw Error(`Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.`);t={}.AZURE_OPENAI_API_KEY}let r={...e.headers};n?.headers&&Object.assign(r,n.headers);let{baseUrl:a,apiVersion:o}=_(e,n);return new i({apiKey:t,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:r,baseURL:a})}function y(e,t,n,r){let i={model:r,input:o(e,t,u),stream:!0,prompt_cache_key:n?.sessionId};return n?.maxTokens&&(i.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(i.temperature=n?.temperature),t.tools&&t.tools.length>0&&(i.tools=c(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(i.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},i.include=[`reasoning.encrypted_content`]):e.thinkingLevelMap?.off!==null&&(i.reasoning={effort:e.thinkingLevelMap?.off??`none`})),i}export{p as streamAzureOpenAIResponses,m as streamSimpleAzureOpenAIResponses};
@@ -1,4 +1,4 @@
1
- import{A as e,C as t,D as n,G as r,H as i,P as a,Q as o,S as s,V as c,_ as l,a as u,at as d,b as f,dt as p,et as m,f as h,g,i as ee,lt as te,nt as _,o as ne,ot as re,s as ie,st as v,tt as y,ut as b}from"./dist-D6ztLqPA.js";import{html as ae,htmlCompletionSource as oe,t as se}from"./dist-UfV1NDbo.js";var ce=class e{static create(t,n,r,i,a){return new e(t,n,r,i+(i<<8)+t+(n<<4)|0,a,[],[])}constructor(e,t,n,r,i,a,o){this.type=e,this.value=t,this.from=n,this.hash=r,this.end=i,this.children=a,this.positions=o,this.hashProp=[[d.contextHash,r]]}addChild(e,t){e.prop(d.contextHash)!=this.hash&&(e=new b(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let n=this.children.length-1;return n>=0&&(t=Math.max(t,this.positions[n]+this.children[n].length+this.from)),new b(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(e,t,n)=>new b(v.none,e,t,n,this.hashProp)})}},x;(function(e){e[e.Document=1]=`Document`,e[e.CodeBlock=2]=`CodeBlock`,e[e.FencedCode=3]=`FencedCode`,e[e.Blockquote=4]=`Blockquote`,e[e.HorizontalRule=5]=`HorizontalRule`,e[e.BulletList=6]=`BulletList`,e[e.OrderedList=7]=`OrderedList`,e[e.ListItem=8]=`ListItem`,e[e.ATXHeading1=9]=`ATXHeading1`,e[e.ATXHeading2=10]=`ATXHeading2`,e[e.ATXHeading3=11]=`ATXHeading3`,e[e.ATXHeading4=12]=`ATXHeading4`,e[e.ATXHeading5=13]=`ATXHeading5`,e[e.ATXHeading6=14]=`ATXHeading6`,e[e.SetextHeading1=15]=`SetextHeading1`,e[e.SetextHeading2=16]=`SetextHeading2`,e[e.HTMLBlock=17]=`HTMLBlock`,e[e.LinkReference=18]=`LinkReference`,e[e.Paragraph=19]=`Paragraph`,e[e.CommentBlock=20]=`CommentBlock`,e[e.ProcessingInstructionBlock=21]=`ProcessingInstructionBlock`,e[e.Escape=22]=`Escape`,e[e.Entity=23]=`Entity`,e[e.HardBreak=24]=`HardBreak`,e[e.Emphasis=25]=`Emphasis`,e[e.StrongEmphasis=26]=`StrongEmphasis`,e[e.Link=27]=`Link`,e[e.Image=28]=`Image`,e[e.InlineCode=29]=`InlineCode`,e[e.HTMLTag=30]=`HTMLTag`,e[e.Comment=31]=`Comment`,e[e.ProcessingInstruction=32]=`ProcessingInstruction`,e[e.Autolink=33]=`Autolink`,e[e.HeaderMark=34]=`HeaderMark`,e[e.QuoteMark=35]=`QuoteMark`,e[e.ListMark=36]=`ListMark`,e[e.LinkMark=37]=`LinkMark`,e[e.EmphasisMark=38]=`EmphasisMark`,e[e.CodeMark=39]=`CodeMark`,e[e.CodeText=40]=`CodeText`,e[e.CodeInfo=41]=`CodeInfo`,e[e.LinkTitle=42]=`LinkTitle`,e[e.LinkLabel=43]=`LinkLabel`,e[e.URL=44]=`URL`})(x||={});var le=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ue=class{constructor(){this.text=``,this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return C(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,n=0){for(let r=t;r<e;r++)n+=this.text.charCodeAt(r)==9?4-n%4:1;return n}findColumn(e){let t=0;for(let n=0;t<this.text.length&&n<e;t++)n+=this.text.charCodeAt(t)==9?4-n%4:1;return t}scrub(){if(!this.baseIndent)return this.text;let e=``;for(let t=0;t<this.basePos;t++)e+=` `;return e+this.text.slice(this.basePos)}};function de(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==x.OrderedList?D:E)(n,t,!1);return r>0&&(e.type!=x.BulletList||w(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}var fe={[x.Blockquote](e,t,n){return n.next==62?(n.markers.push(R(x.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(S(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0):!1},[x.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[x.OrderedList]:de,[x.BulletList]:de,[x.Document](){return!0}};function S(e){return e==32||e==9||e==10||e==13}function C(e,t=0){for(;t<e.length&&S(e.charCodeAt(t));)t++;return t}function pe(e,t,n){for(;t>n&&S(e.charCodeAt(t-1));)t--;return t}function me(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function he(e){return e.next==62?e.text.charCodeAt(e.pos+1)==32?2:1:-1}function w(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let t=e.pos+1;t<e.text.length;t++){let n=e.text.charCodeAt(t);if(n==e.next)r++;else if(!S(n))return-1}return n&&e.next==45&&_e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(we.SetextHeading)>-1||r<3?-1:1}function T(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function E(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||S(e.text.charCodeAt(e.pos+1)))&&(!n||T(t,x.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function D(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){if(r++,r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!S(e.text.charCodeAt(r+1))||n&&!T(t,x.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function ge(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function _e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&S(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}var O=/^[ \t]*$/,ve=/-->/,ye=/\?>/,k=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,ve],[/^\s*<\?/,ye],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,O],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,O]];function be(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let e=0,t=k.length-+!!n;e<t;e++)if(k[e][0].test(r))return e;return-1}function xe(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function A(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==x.CodeText?e[r].to=n:e.push(R(x.CodeText,t,n))}var j={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(A(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){A(s,e.lineStart-1,e.lineStart);for(let e of t.markers)s.push(e)}else if(t.indent<n)break;else{if(s.length){for(let e of s)e.type==x.CodeText?A(o,e.from,e.to):o.push(e);s=[]}A(o,e.lineStart-1,e.lineStart);for(let e of t.markers)o.push(e);a=e.lineStart+t.text.length;let n=e.lineStart+t.findColumn(t.baseIndent+4);n<a&&A(o,n,a)}return s.length&&(s=s.filter(e=>e.type!=x.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(x.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=me(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=pe(t.text,t.text.length,o),c=[R(x.CodeMark,r,r+a)];o<s&&c.push(R(x.CodeInfo,e.lineStart+o,e.lineStart+s));for(let n=!0,r=!0,o=!1;e.nextLine()&&t.depth>=e.stack.length;n=!1){let s=t.pos;if(t.indent-t.baseIndent<4)for(;s<t.text.length&&t.text.charCodeAt(s)==i;)s++;if(s-t.pos>=a&&t.skipSpace(s)==t.text.length){for(let e of t.markers)c.push(e);r&&o&&A(c,e.lineStart-1,e.lineStart),c.push(R(x.CodeMark,e.lineStart+t.pos,e.lineStart+s)),e.nextLine();break}else{o=!0,n||(A(c,e.lineStart-1,e.lineStart),r=!1);for(let e of t.markers)c.push(e);let i=e.lineStart+t.basePos,a=e.lineStart+t.text.length;i<a&&(A(c,i,a),r=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish(x.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=he(t);return n<0?!1:(e.startContext(x.Blockquote,t.pos),e.addNode(x.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(w(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(x.HorizontalRule,n),!0},BulletList(e,t){let n=E(t,e,!1);if(n<0)return!1;e.block.type!=x.BulletList&&e.startContext(x.BulletList,t.basePos,t.next);let r=xe(t,t.pos+1);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=D(t,e,!1);if(n<0)return!1;e.block.type!=x.OrderedList&&e.startContext(x.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=xe(t,t.pos+n);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=ge(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=pe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!S(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(x.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(x.HeaderMark,o-r,a-r);let c=s.finish(x.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,i),!0},HTMLBlock(e,t){let n=be(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=k[n][1],a=[],o=i!=O;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let e of t.markers)a.push(e)}o&&e.nextLine();let s=i==ve?x.CommentBlock:i==ye?x.ProcessingInstructionBlock:x.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,c-r),r),!0},SetextHeading:void 0},Se=class{constructor(e){this.stage=0,this.elts=[],this.pos=0,this.start=e.start,this.advance(e.content)}nextLine(e,t,n){if(this.stage==-1)return!1;let r=n.content+`
1
+ import{A as e,C as t,D as n,G as r,H as i,P as a,Q as o,S as s,V as c,_ as l,a as u,at as d,b as f,dt as p,et as m,f as h,g,i as ee,lt as te,nt as _,o as ne,ot as re,s as ie,st as v,tt as y,ut as b}from"./dist-uJp2dR6X.js";import{html as ae,htmlCompletionSource as oe,t as se}from"./dist-Ck3Vla0r.js";var ce=class e{static create(t,n,r,i,a){return new e(t,n,r,i+(i<<8)+t+(n<<4)|0,a,[],[])}constructor(e,t,n,r,i,a,o){this.type=e,this.value=t,this.from=n,this.hash=r,this.end=i,this.children=a,this.positions=o,this.hashProp=[[d.contextHash,r]]}addChild(e,t){e.prop(d.contextHash)!=this.hash&&(e=new b(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let n=this.children.length-1;return n>=0&&(t=Math.max(t,this.positions[n]+this.children[n].length+this.from)),new b(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(e,t,n)=>new b(v.none,e,t,n,this.hashProp)})}},x;(function(e){e[e.Document=1]=`Document`,e[e.CodeBlock=2]=`CodeBlock`,e[e.FencedCode=3]=`FencedCode`,e[e.Blockquote=4]=`Blockquote`,e[e.HorizontalRule=5]=`HorizontalRule`,e[e.BulletList=6]=`BulletList`,e[e.OrderedList=7]=`OrderedList`,e[e.ListItem=8]=`ListItem`,e[e.ATXHeading1=9]=`ATXHeading1`,e[e.ATXHeading2=10]=`ATXHeading2`,e[e.ATXHeading3=11]=`ATXHeading3`,e[e.ATXHeading4=12]=`ATXHeading4`,e[e.ATXHeading5=13]=`ATXHeading5`,e[e.ATXHeading6=14]=`ATXHeading6`,e[e.SetextHeading1=15]=`SetextHeading1`,e[e.SetextHeading2=16]=`SetextHeading2`,e[e.HTMLBlock=17]=`HTMLBlock`,e[e.LinkReference=18]=`LinkReference`,e[e.Paragraph=19]=`Paragraph`,e[e.CommentBlock=20]=`CommentBlock`,e[e.ProcessingInstructionBlock=21]=`ProcessingInstructionBlock`,e[e.Escape=22]=`Escape`,e[e.Entity=23]=`Entity`,e[e.HardBreak=24]=`HardBreak`,e[e.Emphasis=25]=`Emphasis`,e[e.StrongEmphasis=26]=`StrongEmphasis`,e[e.Link=27]=`Link`,e[e.Image=28]=`Image`,e[e.InlineCode=29]=`InlineCode`,e[e.HTMLTag=30]=`HTMLTag`,e[e.Comment=31]=`Comment`,e[e.ProcessingInstruction=32]=`ProcessingInstruction`,e[e.Autolink=33]=`Autolink`,e[e.HeaderMark=34]=`HeaderMark`,e[e.QuoteMark=35]=`QuoteMark`,e[e.ListMark=36]=`ListMark`,e[e.LinkMark=37]=`LinkMark`,e[e.EmphasisMark=38]=`EmphasisMark`,e[e.CodeMark=39]=`CodeMark`,e[e.CodeText=40]=`CodeText`,e[e.CodeInfo=41]=`CodeInfo`,e[e.LinkTitle=42]=`LinkTitle`,e[e.LinkLabel=43]=`LinkLabel`,e[e.URL=44]=`URL`})(x||={});var le=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ue=class{constructor(){this.text=``,this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return C(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,n=0){for(let r=t;r<e;r++)n+=this.text.charCodeAt(r)==9?4-n%4:1;return n}findColumn(e){let t=0;for(let n=0;t<this.text.length&&n<e;t++)n+=this.text.charCodeAt(t)==9?4-n%4:1;return t}scrub(){if(!this.baseIndent)return this.text;let e=``;for(let t=0;t<this.basePos;t++)e+=` `;return e+this.text.slice(this.basePos)}};function de(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==x.OrderedList?D:E)(n,t,!1);return r>0&&(e.type!=x.BulletList||w(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}var fe={[x.Blockquote](e,t,n){return n.next==62?(n.markers.push(R(x.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(S(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0):!1},[x.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[x.OrderedList]:de,[x.BulletList]:de,[x.Document](){return!0}};function S(e){return e==32||e==9||e==10||e==13}function C(e,t=0){for(;t<e.length&&S(e.charCodeAt(t));)t++;return t}function pe(e,t,n){for(;t>n&&S(e.charCodeAt(t-1));)t--;return t}function me(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function he(e){return e.next==62?e.text.charCodeAt(e.pos+1)==32?2:1:-1}function w(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let t=e.pos+1;t<e.text.length;t++){let n=e.text.charCodeAt(t);if(n==e.next)r++;else if(!S(n))return-1}return n&&e.next==45&&_e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(we.SetextHeading)>-1||r<3?-1:1}function T(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function E(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||S(e.text.charCodeAt(e.pos+1)))&&(!n||T(t,x.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function D(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){if(r++,r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!S(e.text.charCodeAt(r+1))||n&&!T(t,x.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function ge(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function _e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&S(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}var O=/^[ \t]*$/,ve=/-->/,ye=/\?>/,k=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,ve],[/^\s*<\?/,ye],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,O],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,O]];function be(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let e=0,t=k.length-+!!n;e<t;e++)if(k[e][0].test(r))return e;return-1}function xe(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function A(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==x.CodeText?e[r].to=n:e.push(R(x.CodeText,t,n))}var j={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(A(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){A(s,e.lineStart-1,e.lineStart);for(let e of t.markers)s.push(e)}else if(t.indent<n)break;else{if(s.length){for(let e of s)e.type==x.CodeText?A(o,e.from,e.to):o.push(e);s=[]}A(o,e.lineStart-1,e.lineStart);for(let e of t.markers)o.push(e);a=e.lineStart+t.text.length;let n=e.lineStart+t.findColumn(t.baseIndent+4);n<a&&A(o,n,a)}return s.length&&(s=s.filter(e=>e.type!=x.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(x.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=me(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=pe(t.text,t.text.length,o),c=[R(x.CodeMark,r,r+a)];o<s&&c.push(R(x.CodeInfo,e.lineStart+o,e.lineStart+s));for(let n=!0,r=!0,o=!1;e.nextLine()&&t.depth>=e.stack.length;n=!1){let s=t.pos;if(t.indent-t.baseIndent<4)for(;s<t.text.length&&t.text.charCodeAt(s)==i;)s++;if(s-t.pos>=a&&t.skipSpace(s)==t.text.length){for(let e of t.markers)c.push(e);r&&o&&A(c,e.lineStart-1,e.lineStart),c.push(R(x.CodeMark,e.lineStart+t.pos,e.lineStart+s)),e.nextLine();break}else{o=!0,n||(A(c,e.lineStart-1,e.lineStart),r=!1);for(let e of t.markers)c.push(e);let i=e.lineStart+t.basePos,a=e.lineStart+t.text.length;i<a&&(A(c,i,a),r=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish(x.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=he(t);return n<0?!1:(e.startContext(x.Blockquote,t.pos),e.addNode(x.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(w(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(x.HorizontalRule,n),!0},BulletList(e,t){let n=E(t,e,!1);if(n<0)return!1;e.block.type!=x.BulletList&&e.startContext(x.BulletList,t.basePos,t.next);let r=xe(t,t.pos+1);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=D(t,e,!1);if(n<0)return!1;e.block.type!=x.OrderedList&&e.startContext(x.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=xe(t,t.pos+n);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=ge(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=pe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!S(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(x.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(x.HeaderMark,o-r,a-r);let c=s.finish(x.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,i),!0},HTMLBlock(e,t){let n=be(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=k[n][1],a=[],o=i!=O;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let e of t.markers)a.push(e)}o&&e.nextLine();let s=i==ve?x.CommentBlock:i==ye?x.ProcessingInstructionBlock:x.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,c-r),r),!0},SetextHeading:void 0},Se=class{constructor(e){this.stage=0,this.elts=[],this.pos=0,this.start=e.start,this.advance(e.content)}nextLine(e,t,n){if(this.stage==-1)return!1;let r=n.content+`
2
2
  `+t.scrub(),i=this.advance(r);return i>-1&&i<r.length?this.complete(e,n,i):!1}finish(e,t){return(this.stage==2||this.stage==3)&&C(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,n){return e.addLeafElement(t,R(x.LinkReference,this.start,this.start+n,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;)if(this.stage==-1)return-1;else if(this.stage==0){if(!this.nextStage(ze(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(R(x.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Le(e,C(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=C(e,this.pos),n=0;if(t>this.pos){let r=Re(e,t,this.start);if(r){let t=M(e,r.to-this.start);t>0&&(this.nextStage(r),n=t)}}return n||=M(e,this.pos),n>0&&n<e.length?n:-1}else return M(e,this.pos)}};function M(e,t){for(;t<e.length;t++){let n=e.charCodeAt(t);if(n==10)break;if(!S(n))return-1}return t}var Ce=class{nextLine(e,t,n){let r=t.depth<e.stack.length?-1:_e(t),i=t.next;if(r<0)return!1;let a=R(x.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(n,R(i==61?x.SetextHeading1:x.SetextHeading2,n.start,e.prevLineEnd(),[...e.parser.parseInline(n.content,n.start),a])),!0}finish(){return!1}},we={LinkReference(e,t){return t.content.charCodeAt(0)==91?new Se(t):null},SetextHeading(){return new Ce}},Te=[(e,t)=>ge(t)>=0,(e,t)=>me(t)>=0,(e,t)=>he(t)>=0,(e,t)=>E(t,e,!0)>=0,(e,t)=>D(t,e,!0)>=0,(e,t)=>w(t,e,!0)>=0,(e,t)=>be(t,e,!0)>=0],Ee={text:``,end:0},De=class{constructor(e,t,n,r){this.parser=e,this.input=t,this.ranges=r,this.line=new ue,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=ce.create(x.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=n.length?new Ve(n,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let t=0;;){let n=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;t<e.markers.length&&(!n||e.markers[t].from<n.end);){let n=e.markers[t++];this.addNode(n.type,n.from,n.to)}if(!n)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;start:for(;;){for(let t of this.parser.blockParsers)if(t){let n=t(this,e);if(n!=0){if(n==1)return null;e.forward();continue start}}break}let t=new le(this.lineStart+e.pos,e.text.slice(e.pos));for(let e of this.parser.leafBlockParsers)if(e){let n=e(this,t);n&&t.parsers.push(n)}lines:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let n of this.parser.endLeafBlock)if(n(this,e,t))break lines}for(let n of t.parsers)if(n.nextLine(this,e,t))return null;t.content+=`
3
3
  `+e.scrub();for(let n of e.markers)t.marks.push(n)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw RangeError(`Can't move stoppedAt forward`);this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=He(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Ee;if(t.end=e,e>=this.to)t.text=``;else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let e=this.absoluteLineStart,n=this.rangeI;for(;this.ranges[n].to<t.end;){n++;let r=this.ranges[n].from,i=this.lineChunkAt(r);t.end=r+i.length,t.text=t.text.slice(0,this.ranges[n-1].to-e)+i,e=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:n}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=n,e.reset(t);e.depth<this.stack.length;e.depth++){let t=this.stack[e.depth],n=this.parser.skipContextMarkup[t.type];if(!n)throw Error(`Unhandled block context `+x[t.type]);let r=this.line.markers.length;if(!n(t,this,e)){this.line.markers.length>r&&(t.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),n;if(this.input.lineChunks)n=t==`
4
4
  `?``:t;else{let e=t.indexOf(`
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdfjs-BGlny-4w.js","assets/preload-helper-ca-nBW7U.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-ca-nBW7U.js";var t,n=globalThis.process?.release?.name===`node`,r=typeof window<`u`;async function i(e,t={}){let{getDocument:n}=await a();return await n({data:e,isEvalSupported:!1,useSystemFonts:!0,...t}).promise}async function a(){return t||await o(),t}async function o(n,{reload:r=!1}={}){if(!(t&&!r)){if(n)try{t=await c(n());return}catch(e){throw Error(`PDF.js could not be resolved: ${e}`)}try{t=await e(()=>import(`./pdfjs-BGlny-4w.js`),__vite__mapDeps([0,1]))}catch(e){throw Error(`Serverless PDF.js bundle could not be resolved: ${e}`)}}}function s(e){return typeof e==`object`&&!!e&&`_pdfInfo`in e}async function c(e){let t=await e;return t.default||t}var l,u=class{#e=!1;constructor({enableHWA:e=!1}={}){this.#e=e}create(e,t){let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);e.width=t,e.height=n}destroy(e){if(!e.canvas)throw Error(`Canvas is not specified`);e.canvas.width=0,e.canvas.height=0,e.canvas=void 0,e.context=void 0}_createCanvas(e,t){throw Error(`Not implemented`)}},d=class extends u{_document;constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}={}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},f=class extends u{constructor({enableHWA:e=!1}={}){super({enableHWA:e})}_createCanvas(e,t){if(!l)throw Error(`@napi-rs/canvas module is not resolved`);return l.createCanvas(e,t)}};async function p(e){l??=await c(e())}function m(){l&&(globalThis.DOMMatrix===void 0&&(globalThis.DOMMatrix=l.DOMMatrix),globalThis.ImageData===void 0&&(globalThis.ImageData=l.ImageData),globalThis.Path2D===void 0&&(globalThis.Path2D=l.Path2D))}async function h(e,t){let n=s(e)?e:await i(e);if(t<1||t>n.numPages)throw Error(`Invalid page number. Must be between 1 and ${n.numPages}.`);let r=await n.getPage(t),o=await r.getOperatorList(),{OPS:c}=await a(),l=[];for(let e=0;e<o.fnArray.length;e++){if(o.fnArray[e]!==c.paintImageXObject)continue;let t=o.argsArray[e][0],n=await new Promise(e=>(t.startsWith(`g_`)?r.commonObjs:r.objs).get(t,e));if(!n||!n.data||!n.width||!n.height)continue;let{width:i,height:a,data:s}=n,u=s.length/(i*a);if(![1,3,4].includes(u))continue;let d=u;l.push({data:s,width:i,height:a,channels:d,key:t})}return l}async function g(e,t,n={}){let r=await _(n.canvasImport),a=s(e)?e:await i(e,{CanvasFactory:r}),o=await a.getPage(t);if(t<1||t>a.numPages)throw Error(`Invalid page number. Must be between 1 and ${a.numPages}.`);let c=o.getViewport({scale:1}),l=n.scale||1;n.width?l=n.width/c.width:n.height&&(l=n.height/c.height);let u=o.getViewport({scale:Math.max(0,l)}),d=new r().create(u.width,u.height);await o.render({canvas:d.canvas,canvasContext:d.context,viewport:u}).promise;let f=d.canvas.toDataURL();return n.toDataURL?f:await(await fetch(f)).arrayBuffer()}async function _(e){if(r)return d;if(n){if(!e)throw Error(`Parameter "canvasImport" is required in Node.js environment.`);return await p(e),m(),f}throw Error(`Unsupported environment for canvas creation.`)}async function v(e){let t=s(e)?e:await i(e),n=await Promise.all(Array.from({length:t.numPages},(e,n)=>y(t,n+1)));return{totalPages:t.numPages,links:n.flat()}}async function y(e,t){let n=await(await e.getPage(t)).getAnnotations(),r=[];for(let e of n)e.subtype===`Link`&&e.url&&r.push(e.url);return r}var b=[`xmp:createdate`,`xmp:modifydate`,`xmp:metadatadate`,`xap:createdate`,`xap:modifydate`,`xap:metadatadate`];async function x(e,t={}){let n=await(s(e)?e:await i(e)).getMetadata(),r=n?.info||{};if(t.parseDates){let{PDFDateString:e}=await a();r?.CreationDate&&(r.CreationDate=e.toDateObject(r?.CreationDate)),r?.ModDate&&(r.ModDate=e.toDateObject(r?.ModDate)),n.metadata&&=new Proxy(n.metadata,{get(e,t){return t===`get`?t=>{let n=e.get(t);return b.includes(t)&&n?S(n):n}:e[t]}})}return{info:r,metadata:n?.metadata||{}}}function S(e){if(!e)return;let t=Date.parse(e);if(!Number.isNaN(t))return new Date(t)}async function C(e,t={}){let{mergePages:n=!1}=t,r=s(e)?e:await i(e),a=await Promise.all(Array.from({length:r.numPages},(e,t)=>w(r,t+1)));return{totalPages:r.numPages,text:n?a.join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/pdfjs-C0bwNEC1.js","assets/preload-helper-ca-nBW7U.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-ca-nBW7U.js";var t,n=globalThis.process?.release?.name===`node`,r=typeof window<`u`;async function i(e,t={}){let{getDocument:n}=await a();return await n({data:e,isEvalSupported:!1,useSystemFonts:!0,...t}).promise}async function a(){return t||await o(),t}async function o(n,{reload:r=!1}={}){if(!(t&&!r)){if(n)try{t=await c(n());return}catch(e){throw Error(`PDF.js could not be resolved: ${e}`)}try{t=await e(()=>import(`./pdfjs-C0bwNEC1.js`),__vite__mapDeps([0,1]))}catch(e){throw Error(`Serverless PDF.js bundle could not be resolved: ${e}`)}}}function s(e){return typeof e==`object`&&!!e&&`_pdfInfo`in e}async function c(e){let t=await e;return t.default||t}var l,u=class{#e=!1;constructor({enableHWA:e=!1}={}){this.#e=e}create(e,t){let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset({canvas:e},t,n){if(!e)throw Error(`Canvas is not specified`);e.width=t,e.height=n}destroy(e){if(!e.canvas)throw Error(`Canvas is not specified`);e.canvas.width=0,e.canvas.height=0,e.canvas=void 0,e.context=void 0}_createCanvas(e,t){throw Error(`Not implemented`)}},d=class extends u{_document;constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}={}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},f=class extends u{constructor({enableHWA:e=!1}={}){super({enableHWA:e})}_createCanvas(e,t){if(!l)throw Error(`@napi-rs/canvas module is not resolved`);return l.createCanvas(e,t)}};async function p(e){l??=await c(e())}function m(){l&&(globalThis.DOMMatrix===void 0&&(globalThis.DOMMatrix=l.DOMMatrix),globalThis.ImageData===void 0&&(globalThis.ImageData=l.ImageData),globalThis.Path2D===void 0&&(globalThis.Path2D=l.Path2D))}async function h(e,t){let n=s(e)?e:await i(e);if(t<1||t>n.numPages)throw Error(`Invalid page number. Must be between 1 and ${n.numPages}.`);let r=await n.getPage(t),o=await r.getOperatorList(),{OPS:c}=await a(),l=[];for(let e=0;e<o.fnArray.length;e++){if(o.fnArray[e]!==c.paintImageXObject)continue;let t=o.argsArray[e][0],n=await new Promise(e=>(t.startsWith(`g_`)?r.commonObjs:r.objs).get(t,e));if(!n||!n.data||!n.width||!n.height)continue;let{width:i,height:a,data:s}=n,u=s.length/(i*a);if(![1,3,4].includes(u))continue;let d=u;l.push({data:s,width:i,height:a,channels:d,key:t})}return l}async function g(e,t,n={}){let r=await _(n.canvasImport),a=s(e)?e:await i(e,{CanvasFactory:r}),o=await a.getPage(t);if(t<1||t>a.numPages)throw Error(`Invalid page number. Must be between 1 and ${a.numPages}.`);let c=o.getViewport({scale:1}),l=n.scale||1;n.width?l=n.width/c.width:n.height&&(l=n.height/c.height);let u=o.getViewport({scale:Math.max(0,l)}),d=new r().create(u.width,u.height);await o.render({canvas:d.canvas,canvasContext:d.context,viewport:u}).promise;let f=d.canvas.toDataURL();return n.toDataURL?f:await(await fetch(f)).arrayBuffer()}async function _(e){if(r)return d;if(n){if(!e)throw Error(`Parameter "canvasImport" is required in Node.js environment.`);return await p(e),m(),f}throw Error(`Unsupported environment for canvas creation.`)}async function v(e){let t=s(e)?e:await i(e),n=await Promise.all(Array.from({length:t.numPages},(e,n)=>y(t,n+1)));return{totalPages:t.numPages,links:n.flat()}}async function y(e,t){let n=await(await e.getPage(t)).getAnnotations(),r=[];for(let e of n)e.subtype===`Link`&&e.url&&r.push(e.url);return r}var b=[`xmp:createdate`,`xmp:modifydate`,`xmp:metadatadate`,`xap:createdate`,`xap:modifydate`,`xap:metadatadate`];async function x(e,t={}){let n=await(s(e)?e:await i(e)).getMetadata(),r=n?.info||{};if(t.parseDates){let{PDFDateString:e}=await a();r?.CreationDate&&(r.CreationDate=e.toDateObject(r?.CreationDate)),r?.ModDate&&(r.ModDate=e.toDateObject(r?.ModDate)),n.metadata&&=new Proxy(n.metadata,{get(e,t){return t===`get`?t=>{let n=e.get(t);return b.includes(t)&&n?S(n):n}:e[t]}})}return{info:r,metadata:n?.metadata||{}}}function S(e){if(!e)return;let t=Date.parse(e);if(!Number.isNaN(t))return new Date(t)}async function C(e,t={}){let{mergePages:n=!1}=t,r=s(e)?e:await i(e),a=await Promise.all(Array.from({length:r.numPages},(e,t)=>w(r,t+1)));return{totalPages:r.numPages,text:n?a.join(`
3
3
  `).replace(/\s+/g,` `):a}}async function w(e,t){return(await(await e.getPage(t)).getTextContent()).items.filter(e=>e.str!=null).map(e=>e.str+(e.hasEOL?`
4
4
  `:``)).join(``)}async function T(e){await o(e,{reload:!0})}async function E(e){await o(e.pdfjs,{reload:!0})}var D=async(...e)=>(await o(),await x(...e)),O=async(...e)=>(await o(),await C(...e)),k=async(...e)=>(await o(),await h(...e)),A=async(...e)=>(await o(),await g(...e)),j=async(...e)=>(await o(),await v(...e));export{E as configureUnPDF,_ as createIsomorphicCanvasFactory,T as definePDFJSModule,k as extractImages,j as extractLinks,O as extractText,i as getDocumentProxy,D as getMeta,a as getResolvedPDFJS,A as renderPageAsImage,o as resolvePDFJSImport};