first commit
SAP-ERP Portal CI/CD / build (push) Failing after 5m20s

This commit is contained in:
John
2026-09-23 17:31:02 +05:30
commit 69b4e68baf
51657 changed files with 3864077 additions and 0 deletions
+49
View File
@@ -0,0 +1,49 @@
import { type BaseAnthropic } from "../client.mjs";
import { type PromiseOrValue } from "../internal/types.mjs";
import { type APIResponseProps, type WithRequestID } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
#private;
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(client: BaseAnthropic, responsePromise: Promise<APIResponseProps>, parseResponse?: (client: BaseAnthropic, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
withResponse(): Promise<{
data: T;
response: Response;
request_id: string | null | undefined;
}>;
private parse;
then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<WithRequestID<T> | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>>;
}
//# sourceMappingURL=api-promise.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.mts","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,aAAa,EAAE;OAEtB,EAAE,KAAK,cAAc,EAAE;OACvB,EACL,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAGnB;AAED;;;GAGG;AACH,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;;IAMxD,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,aAAa;IANvB,OAAO,CAAC,aAAa,CAAwC;gBAI3D,MAAM,EAAE,aAAa,EACb,eAAe,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAC1C,aAAa,GAAE,CACrB,MAAM,EAAE,aAAa,EACrB,KAAK,EAAE,gBAAgB,KACpB,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAwB;IAW9D,WAAW,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,KAAK,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAMjF;;;;;;;;;;OAUG;IACH,UAAU,IAAI,OAAO,CAAC,QAAQ,CAAC;IAI/B;;;;;;;;;;;OAWG;IACG,YAAY,IAAI,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAC;QAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;KAAE,CAAC;IAKrG,OAAO,CAAC,KAAK;IASJ,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,QAAQ,GAAG,KAAK,EACzD,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,EAChG,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAClF,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAItB,KAAK,CAAC,OAAO,GAAG,KAAK,EAC5B,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAChF,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;IAI7B,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAGzF"}
+49
View File
@@ -0,0 +1,49 @@
import { type BaseAnthropic } from "../client.js";
import { type PromiseOrValue } from "../internal/types.js";
import { type APIResponseProps, type WithRequestID } from "../internal/parse.js";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
#private;
private responsePromise;
private parseResponse;
private parsedPromise;
constructor(client: BaseAnthropic, responsePromise: Promise<APIResponseProps>, parseResponse?: (client: BaseAnthropic, props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
_thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U>;
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse(): Promise<Response>;
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
withResponse(): Promise<{
data: T;
response: Response;
request_id: string | null | undefined;
}>;
private parse;
then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<WithRequestID<T> | TResult>;
finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>>;
}
//# sourceMappingURL=api-promise.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.d.ts","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":"OAEO,EAAE,KAAK,aAAa,EAAE;OAEtB,EAAE,KAAK,cAAc,EAAE;OACvB,EACL,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAGnB;AAED;;;GAGG;AACH,qBAAa,UAAU,CAAC,CAAC,CAAE,SAAQ,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;;IAMxD,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,aAAa;IANvB,OAAO,CAAC,aAAa,CAAwC;gBAI3D,MAAM,EAAE,aAAa,EACb,eAAe,EAAE,OAAO,CAAC,gBAAgB,CAAC,EAC1C,aAAa,GAAE,CACrB,MAAM,EAAE,aAAa,EACrB,KAAK,EAAE,gBAAgB,KACpB,cAAc,CAAC,aAAa,CAAC,CAAC,CAAC,CAAwB;IAW9D,WAAW,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,gBAAgB,KAAK,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC;IAMjF;;;;;;;;;;OAUG;IACH,UAAU,IAAI,OAAO,CAAC,QAAQ,CAAC;IAI/B;;;;;;;;;;;OAWG;IACG,YAAY,IAAI,OAAO,CAAC;QAAE,IAAI,EAAE,CAAC,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAC;QAAC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAA;KAAE,CAAC;IAKrG,OAAO,CAAC,KAAK;IASJ,IAAI,CAAC,QAAQ,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,QAAQ,GAAG,KAAK,EACzD,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,EAChG,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,QAAQ,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAClF,OAAO,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAItB,KAAK,CAAC,OAAO,GAAG,KAAK,EAC5B,UAAU,CAAC,EAAE,CAAC,CAAC,MAAM,EAAE,GAAG,KAAK,OAAO,GAAG,WAAW,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,GAAG,IAAI,GAChF,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC;IAI7B,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CAGzF"}
+76
View File
@@ -0,0 +1,76 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIPromise = void 0;
const tslib_1 = require("../internal/tslib.js");
const parse_1 = require("../internal/parse.js");
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = parse_1.defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
tslib_1.__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => (0, parse_1.addRequestID)(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response, request_id: response.headers.get('request-id') };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_1.__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
exports.APIPromise = APIPromise;
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.js","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;AAKtF,gDAK2B;AAE3B;;;GAGG;AACH,MAAa,UAAc,SAAQ,OAAyB;IAI1D,YACE,MAAqB,EACb,eAA0C,EAC1C,gBAGgC,4BAAoB;QAE5D,KAAK,CAAC,CAAC,OAAO,EAAE,EAAE;YAChB,yEAAyE;YACzE,0EAA0E;YAC1E,wBAAwB;YACxB,OAAO,CAAC,IAAW,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC;QAXK,oBAAe,GAAf,eAAe,CAA2B;QAC1C,kBAAa,GAAb,aAAa,CAGuC;QAR9D,qCAAuB;QAgBrB,+BAAA,IAAI,sBAAW,MAAM,MAAA,CAAC;IACxB,CAAC;IAED,WAAW,CAAI,SAAkD;QAC/D,OAAO,IAAI,UAAU,CAAC,+BAAA,IAAI,0BAAQ,EAAE,IAAI,CAAC,eAAe,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAChF,IAAA,oBAAY,EAAC,SAAS,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,EAAE,KAAK,CAAC,QAAQ,CAAC,CACxF,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,UAAU;QACR,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;IACtD,CAAC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,YAAY;QAChB,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;QAC9E,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;IAC5E,CAAC;IAEO,KAAK;QACX,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACxB,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,CAC5C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,+BAAA,IAAI,0BAAQ,EAAE,IAAI,CAAqC,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEQ,IAAI,CACX,WAAgG,EAChG,UAAmF;QAEnF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAEQ,KAAK,CACZ,UAAiF;QAEjF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAEQ,OAAO,CAAC,SAA2C;QAC1D,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;CACF;AApFD,gCAoFC"}
+72
View File
@@ -0,0 +1,72 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _APIPromise_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { defaultParseResponse, addRequestID, } from "../internal/parse.mjs";
/**
* A subclass of `Promise` providing additional helper methods
* for interacting with the SDK.
*/
export class APIPromise extends Promise {
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
super((resolve) => {
// this is maybe a bit weird but this has to be a no-op to not implicitly
// parse the response body; instead .then, .catch, .finally are overridden
// to parse the response
resolve(null);
});
this.responsePromise = responsePromise;
this.parseResponse = parseResponse;
_APIPromise_client.set(this, void 0);
__classPrivateFieldSet(this, _APIPromise_client, client, "f");
}
_thenUnwrap(transform) {
return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response));
}
/**
* Gets the raw `Response` instance instead of parsing the response
* data.
*
* If you want to parse the response body but still get the `Response`
* instance, you can use {@link withResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
asResponse() {
return this.responsePromise.then((p) => p.response);
}
/**
* Gets the parsed response data, the raw `Response` instance and the ID of the request,
* returned via the `request-id` header which is useful for debugging requests and resporting
* issues to Anthropic.
*
* If you just want to get the raw `Response` instance without parsing it,
* you can use {@link asResponse()}.
*
* 👋 Getting the wrong TypeScript type for `Response`?
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
* to your `tsconfig.json`.
*/
async withResponse() {
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
return { data, response, request_id: response.headers.get('request-id') };
}
parse() {
if (!this.parsedPromise) {
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data));
}
return this.parsedPromise;
}
then(onfulfilled, onrejected) {
return this.parse().then(onfulfilled, onrejected);
}
catch(onrejected) {
return this.parse().catch(onrejected);
}
finally(onfinally) {
return this.parse().finally(onfinally);
}
}
_APIPromise_client = new WeakMap();
//# sourceMappingURL=api-promise.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"api-promise.mjs","sourceRoot":"","sources":["../src/core/api-promise.ts"],"names":[],"mappings":"AAAA,sFAAsF;;;OAK/E,EAGL,oBAAoB,EACpB,YAAY,GACb;AAED;;;GAGG;AACH,MAAM,OAAO,UAAc,SAAQ,OAAyB;IAI1D,YACE,MAAqB,EACb,eAA0C,EAC1C,gBAGgC,oBAAoB;QAE5D,KAAK,CAAC,CAAC,OAAO,EAAE,EAAE;YAChB,yE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,EAAE,IAAI,CAAqC,CACrF,CAAC;QACJ,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAEQ,IAAI,CACX,WAAgG,EAChG,UAAmF;QAEnF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,CAAC,WAAW,EAAE,UAAU,CAAC,CAAC;IACpD,CAAC;IAEQ,KAAK,CACZ,UAAiF;QAEjF,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACxC,CAAC;IAEQ,OAAO,CAAC,SAA2C;QAC1D,OAAO,IAAI,CAAC,KAAK,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACzC,CAAC;CACF"}
+131
View File
@@ -0,0 +1,131 @@
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CONFIG_FILE_VERSION = "1.0";
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CREDENTIALS_FILE_VERSION = "1.0";
/**
* Authentication-mode-specific configuration. On the wire (configs/<profile>.json)
* this is a flat JSON object under the top-level `authentication` key — `type`,
* `credentials_path`, and the variant-specific fields all sit at the same level.
*
* Unknown fields are silently ignored for forward compatibility. Unknown
* authentication types are rejected because the SDK has no way to resolve
* credentials for them.
*/
export type AuthenticationInfo = {
/**
* Filesystem path to the credentials JSON that stores access/refresh tokens.
* Defaults to `<config_dir>/credentials/<profile>.json` when omitted.
*/
credentials_path?: string | undefined;
} & ({
type: 'oidc_federation';
/** Tagged ID (`fdrl_...`) of the federation rule. Required. */
federation_rule_id: string;
/** Optional `svac_...` expected-target check. */
service_account_id?: string | undefined;
identity_token?: {
source: 'file';
path: string;
} | undefined;
/** Display-only; the SDK does not send this on the jwt-bearer exchange. */
scope?: string | undefined;
} | {
type: 'user_oauth';
/** OAuth client ID for refresh. Empty → access token is treated as static. */
client_id?: string | undefined;
/** Display-only; the SDK does not send this on refresh. */
scope?: string | undefined;
/** Console URL the profile was created against. Display-only. */
console_url?: string | undefined;
});
export type AnthropicConfig = {
version?: string;
authentication: AuthenticationInfo;
base_url?: string | undefined;
organization_id?: string | undefined;
workspace_id?: string | undefined;
};
export type AnthropicCredentials = {
version?: string;
type: 'oauth_token';
access_token: string;
expires_at?: number;
refresh_token?: string;
scope?: string;
organization_uuid?: string;
organization_name?: string;
account_email?: string;
};
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export declare const loadConfig: (profile?: string) => Promise<AnthropicConfig | null>;
/**
* Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`
* when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the
* config was synthesized purely from environment variables.
*
* The credential chain uses this distinction to decide whether to back the
* federation exchange with a disk cache: file-backed profiles get a cache at
* `<config_dir>/credentials/<profile>.json`, env-only configs do not.
*/
export type LoadedConfig = {
config: AnthropicConfig;
fromFile: boolean;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export declare const loadConfigWithSource: (profile?: string) => Promise<LoadedConfig | null>;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export declare const loadCredentials: () => Promise<AnthropicCredentials | null>;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export declare const getCredentialsPath: (config: AnthropicConfig | null, profile?: string) => Promise<string | null>;
//# sourceMappingURL=credentials.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"credentials.d.mts","sourceRoot":"","sources":["../src/core/credentials.ts"],"names":[],"mappings":"AAGA,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,8FAA8F;AAC9F,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACvC,GAAG,CACA;IACE,IAAI,EAAE,iBAAiB,CAAC;IACxB,+DAA+D;IAC/D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,kBAAkB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,cAAc,CAAC,EACX;QACE,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;KACd,G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AAO,MAAM,oBAAoB,GAAU,UAAU,MAAM,KAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CA8FxF,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,eAAe,QAAa,OAAO,CAAC,oBAAoB,GAAG,IAAI,CA8B3E,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,eAAe,GAAG,IAAI,EAC9B,UAAU,MAAM,KACf,OAAO,CAAC,MAAM,GAAG,IAAI,CAkBvB,CAAC"}
+131
View File
@@ -0,0 +1,131 @@
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CONFIG_FILE_VERSION = "1.0";
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export declare const CREDENTIALS_FILE_VERSION = "1.0";
/**
* Authentication-mode-specific configuration. On the wire (configs/<profile>.json)
* this is a flat JSON object under the top-level `authentication` key — `type`,
* `credentials_path`, and the variant-specific fields all sit at the same level.
*
* Unknown fields are silently ignored for forward compatibility. Unknown
* authentication types are rejected because the SDK has no way to resolve
* credentials for them.
*/
export type AuthenticationInfo = {
/**
* Filesystem path to the credentials JSON that stores access/refresh tokens.
* Defaults to `<config_dir>/credentials/<profile>.json` when omitted.
*/
credentials_path?: string | undefined;
} & ({
type: 'oidc_federation';
/** Tagged ID (`fdrl_...`) of the federation rule. Required. */
federation_rule_id: string;
/** Optional `svac_...` expected-target check. */
service_account_id?: string | undefined;
identity_token?: {
source: 'file';
path: string;
} | undefined;
/** Display-only; the SDK does not send this on the jwt-bearer exchange. */
scope?: string | undefined;
} | {
type: 'user_oauth';
/** OAuth client ID for refresh. Empty → access token is treated as static. */
client_id?: string | undefined;
/** Display-only; the SDK does not send this on refresh. */
scope?: string | undefined;
/** Console URL the profile was created against. Display-only. */
console_url?: string | undefined;
});
export type AnthropicConfig = {
version?: string;
authentication: AuthenticationInfo;
base_url?: string | undefined;
organization_id?: string | undefined;
workspace_id?: string | undefined;
};
export type AnthropicCredentials = {
version?: string;
type: 'oauth_token';
access_token: string;
expires_at?: number;
refresh_token?: string;
scope?: string;
organization_uuid?: string;
organization_name?: string;
account_email?: string;
};
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export declare const loadConfig: (profile?: string) => Promise<AnthropicConfig | null>;
/**
* Source-tagged result of {@link loadConfigWithSource}. `fromFile` is `true`
* when `<config_dir>/configs/<profile>.json` exists on disk; `false` when the
* config was synthesized purely from environment variables.
*
* The credential chain uses this distinction to decide whether to back the
* federation exchange with a disk cache: file-backed profiles get a cache at
* `<config_dir>/credentials/<profile>.json`, env-only configs do not.
*/
export type LoadedConfig = {
config: AnthropicConfig;
fromFile: boolean;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export declare const loadConfigWithSource: (profile?: string) => Promise<LoadedConfig | null>;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export declare const loadCredentials: () => Promise<AnthropicCredentials | null>;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export declare const getCredentialsPath: (config: AnthropicConfig | null, profile?: string) => Promise<string | null>;
//# sourceMappingURL=credentials.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/core/credentials.ts"],"names":[],"mappings":"AAGA,0FAA0F;AAC1F,eAAO,MAAM,mBAAmB,QAAQ,CAAC;AACzC,8FAA8F;AAC9F,eAAO,MAAM,wBAAwB,QAAQ,CAAC;AAE9C;;;;;;;;GAQG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACvC,GAAG,CACA;IACE,IAAI,EAAE,iBAAiB,CAAC;IACxB,+DAA+D;IAC/D,kBAAkB,EAAE,MAAM,CAAC;IAC3B,iDAAiD;IACjD,kBAAkB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC,cAAc,CAAC,EACX;QACE,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;KACd,GACD,SAAS,CAAC;IACd,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B,GACD;IACE,IAAI,EAAE,YAAY,CAAC;I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eAAO,MAAM,eAAe,QAAa,OAAO,CAAC,oBAAoB,GAAG,IAAI,CA8B3E,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,QAAQ,eAAe,GAAG,IAAI,EAC9B,UAAU,MAAM,KACf,OAAO,CAAC,MAAM,GAAG,IAAI,CAkBvB,CAAC"}
+317
View File
@@ -0,0 +1,317 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCredentialsPath = exports.loadCredentials = exports.loadConfigWithSource = exports.loadConfig = exports.CREDENTIALS_FILE_VERSION = exports.CONFIG_FILE_VERSION = void 0;
const detect_platform_1 = require("../internal/detect-platform.js");
const utils_1 = require("../internal/utils.js");
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
exports.CONFIG_FILE_VERSION = '1.0';
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
exports.CREDENTIALS_FILE_VERSION = '1.0';
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
function validateProfileName(name) {
if (!name) {
throw new Error('profile name is empty');
}
if (name === '.' || name === '..') {
throw new Error(`profile name "${name}" is not allowed`);
}
if (name.includes('/') || name.includes('\\')) {
throw new Error(`profile name "${name}" must not contain path separators`);
}
if (!PROFILE_NAME_PATTERN.test(name)) {
throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`);
}
}
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
const loadConfig = async (profile) => {
return (await (0, exports.loadConfigWithSource)(profile))?.config ?? null;
};
exports.loadConfig = loadConfig;
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
const loadConfigWithSource = async (profile) => {
var _a, _b;
const rootConfigPath = await getRootConfigPath();
if (rootConfigPath === null) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (profileName === null) {
return null;
}
validateProfileName(profileName);
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
let configRaw;
try {
configRaw = await fs.promises.readFile(configPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read config file ${configPath}: ${err}`);
}
configRaw = null;
}
if (configRaw === null) {
const organizationId = (0, utils_1.readEnv)('ANTHROPIC_ORGANIZATION_ID');
const identityTokenFile = (0, utils_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN_FILE');
const federationRuleId = (0, utils_1.readEnv)('ANTHROPIC_FEDERATION_RULE_ID');
if (federationRuleId && organizationId) {
return {
fromFile: false,
config: {
organization_id: organizationId,
// A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
// treated as unset — readEnv coerces empty to undefined, and the body
// builder's truthy check skips it — so `"workspace_id": ""` never goes
// on the wire.
workspace_id: (0, utils_1.readEnv)('ANTHROPIC_WORKSPACE_ID'),
base_url: (0, utils_1.readEnv)('ANTHROPIC_BASE_URL'),
authentication: {
type: 'oidc_federation',
federation_rule_id: federationRuleId,
service_account_id: (0, utils_1.readEnv)('ANTHROPIC_SERVICE_ACCOUNT_ID'),
identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
scope: (0, utils_1.readEnv)('ANTHROPIC_SCOPE'),
},
},
};
}
return null;
}
let config;
try {
config = JSON.parse(configRaw);
}
catch (err) {
throw new Error(`failed to parse config file ${configPath}: ${err}`);
}
if (!config.authentication) {
throw new Error(`config file ${configPath} is missing "authentication"`);
}
const authType = config.authentication.type;
if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
}
// File values are authoritative; env vars only fill fields the file left unset.
config.organization_id ?? (config.organization_id = (0, utils_1.readEnv)('ANTHROPIC_ORGANIZATION_ID'));
config.workspace_id ?? (config.workspace_id = (0, utils_1.readEnv)('ANTHROPIC_WORKSPACE_ID'));
config.base_url ?? (config.base_url = (0, utils_1.readEnv)('ANTHROPIC_BASE_URL'));
(_a = config.authentication).scope ?? (_a.scope = (0, utils_1.readEnv)('ANTHROPIC_SCOPE'));
if (config.authentication.type === 'oidc_federation') {
if (!config.authentication.identity_token) {
const identityTokenFile = (0, utils_1.readEnv)('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (identityTokenFile) {
config.authentication.identity_token = {
source: 'file',
path: identityTokenFile,
};
}
}
// Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
// to '' so the type stays `string` (always set). The downstream required
// check in credential-chain rejects empty, so semantics match but types are
// cleaner.
if (!config.authentication.federation_rule_id) {
config.authentication.federation_rule_id = (0, utils_1.readEnv)('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
}
(_b = config.authentication).service_account_id ?? (_b.service_account_id = (0, utils_1.readEnv)('ANTHROPIC_SERVICE_ACCOUNT_ID'));
}
return { config, fromFile: true };
};
exports.loadConfigWithSource = loadConfigWithSource;
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
const loadCredentials = async () => {
const config = await (0, exports.loadConfig)();
const credentialsPath = await (0, exports.getCredentialsPath)(config);
if (!credentialsPath) {
return null;
}
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
let raw;
try {
raw = await fs.promises.readFile(credentialsPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
}
return null;
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
}
if (creds.type && creds.type !== 'oauth_token') {
throw new Error(`credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`);
}
return creds;
};
exports.loadCredentials = loadCredentials;
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
const getCredentialsPath = async (config, profile) => {
if (config?.authentication.credentials_path) {
return config.authentication.credentials_path;
}
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (!profileName) {
return null;
}
validateProfileName(profileName);
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
};
exports.getCredentialsPath = getCredentialsPath;
const getRootConfigPath = async () => {
if (!supportsLocalConfigFiles()) {
return null;
}
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
// ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
// process operator, not by remote input, so it is not validated.
const configDir = (0, utils_1.readEnv)('ANTHROPIC_CONFIG_DIR');
if (configDir) {
return configDir;
}
const os = (0, detect_platform_1.getPlatformHeaders)()['X-Stainless-OS'];
if (os === 'Windows') {
const appData = (0, utils_1.readEnv)('APPDATA');
if (appData) {
return path.join(appData, 'Anthropic');
}
const userProfile = (0, utils_1.readEnv)('USERPROFILE');
if (userProfile) {
return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
}
// No usable Windows config root — return null so callers fall through to
// "no config available" rather than silently writing under C:\.
return null;
}
const xdgConfigHome = (0, utils_1.readEnv)('XDG_CONFIG_HOME');
if (xdgConfigHome) {
return path.join(xdgConfigHome, 'anthropic');
}
const home = (0, utils_1.readEnv)('HOME');
if (home) {
return path.join(home, '.config', 'anthropic');
}
return null;
};
const supportsLocalConfigFiles = () => {
const runtime = (0, detect_platform_1.getPlatformHeaders)()['X-Stainless-Runtime'];
return runtime === 'node' || runtime === 'deno';
};
const getActiveProfileName = async () => {
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = (0, utils_1.readEnv)('ANTHROPIC_PROFILE');
if (profileName) {
return profileName;
}
const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
const path = await Promise.resolve().then(() => __importStar(require('node:path')));
const filePath = path.join(rootConfigPath, 'active_config');
try {
return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read ${filePath}: ${err}`);
}
return 'default';
}
};
//# sourceMappingURL=credentials.js.map
File diff suppressed because one or more lines are too long
+277
View File
@@ -0,0 +1,277 @@
import { getPlatformHeaders } from "../internal/detect-platform.mjs";
import { readEnv } from "../internal/utils.mjs";
/** Current schema version written to `configs/<profile>.json`. Absent on read ⇒ "1.0". */
export const CONFIG_FILE_VERSION = '1.0';
/** Current schema version written to `credentials/<profile>.json`. Absent on read ⇒ "1.0". */
export const CREDENTIALS_FILE_VERSION = '1.0';
const PROFILE_NAME_PATTERN = /^[A-Za-z0-9_.-]+$/;
function validateProfileName(name) {
if (!name) {
throw new Error('profile name is empty');
}
if (name === '.' || name === '..') {
throw new Error(`profile name "${name}" is not allowed`);
}
if (name.includes('/') || name.includes('\\')) {
throw new Error(`profile name "${name}" must not contain path separators`);
}
if (!PROFILE_NAME_PATTERN.test(name)) {
throw new Error(`profile name "${name}" contains disallowed characters (allowed: letters, digits, '_', '.', '-')`);
}
}
/**
* Loads the Anthropic configuration for the given (or active) profile.
*
* Returns `null` when running in a browser or no configuration can be resolved.
* Otherwise, returns the configuration based on the config file and environment variables.
*
* **Profile resolution** (first match wins):
* 1. Explicit `profile` argument
* 2. `ANTHROPIC_PROFILE` environment variable
* 3. Contents of `<config_dir>/active_config` file
* 4. `"default"`
*
* **Config resolution:**
* - If `<config_dir>/configs/<profile>.json` exists, it is loaded and
* missing fields are filled from environment variables. Values present
* in the file take precedence — env vars only fill gaps:
* - `ANTHROPIC_BASE_URL` → `base_url`
* - `ANTHROPIC_ORGANIZATION_ID` → `organization_id`
* - `ANTHROPIC_WORKSPACE_ID` → `workspace_id`
* - `ANTHROPIC_SCOPE` → `authentication.scope`
* - `ANTHROPIC_FEDERATION_RULE_ID` → `authentication.federation_rule_id` (oidc_federation)
* - `ANTHROPIC_IDENTITY_TOKEN_FILE` → `authentication.identity_token` (oidc_federation)
* - `ANTHROPIC_SERVICE_ACCOUNT_ID` → `authentication.service_account_id` (oidc_federation)
* - If no config file exists, an `oidc_federation` config is synthesized
* entirely from environment variables when both `ANTHROPIC_FEDERATION_RULE_ID`
* and `ANTHROPIC_ORGANIZATION_ID` are set.
*/
export const loadConfig = async (profile) => {
return (await loadConfigWithSource(profile))?.config ?? null;
};
/**
* Same as {@link loadConfig}, but also reports whether the config was loaded
* from a profile file on disk (`fromFile: true`) or synthesized entirely from
* environment variables (`fromFile: false`).
*/
export const loadConfigWithSource = async (profile) => {
var _a, _b;
const rootConfigPath = await getRootConfigPath();
if (rootConfigPath === null) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (profileName === null) {
return null;
}
validateProfileName(profileName);
const fs = await import('node:fs');
const path = await import('node:path');
const configPath = path.join(rootConfigPath, 'configs', `${profileName}.json`);
let configRaw;
try {
configRaw = await fs.promises.readFile(configPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read config file ${configPath}: ${err}`);
}
configRaw = null;
}
if (configRaw === null) {
const organizationId = readEnv('ANTHROPIC_ORGANIZATION_ID');
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
const federationRuleId = readEnv('ANTHROPIC_FEDERATION_RULE_ID');
if (federationRuleId && organizationId) {
return {
fromFile: false,
config: {
organization_id: organizationId,
// A defaulted-but-empty CI variable (`ANTHROPIC_WORKSPACE_ID=""`) is
// treated as unset — readEnv coerces empty to undefined, and the body
// builder's truthy check skips it — so `"workspace_id": ""` never goes
// on the wire.
workspace_id: readEnv('ANTHROPIC_WORKSPACE_ID'),
base_url: readEnv('ANTHROPIC_BASE_URL'),
authentication: {
type: 'oidc_federation',
federation_rule_id: federationRuleId,
service_account_id: readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'),
identity_token: identityTokenFile ? { source: 'file', path: identityTokenFile } : undefined,
scope: readEnv('ANTHROPIC_SCOPE'),
},
},
};
}
return null;
}
let config;
try {
config = JSON.parse(configRaw);
}
catch (err) {
throw new Error(`failed to parse config file ${configPath}: ${err}`);
}
if (!config.authentication) {
throw new Error(`config file ${configPath} is missing "authentication"`);
}
const authType = config.authentication.type;
if (authType !== 'oidc_federation' && authType !== 'user_oauth') {
throw new Error(`authentication.type "${authType}" is not a known authentication type`);
}
// File values are authoritative; env vars only fill fields the file left unset.
config.organization_id ?? (config.organization_id = readEnv('ANTHROPIC_ORGANIZATION_ID'));
config.workspace_id ?? (config.workspace_id = readEnv('ANTHROPIC_WORKSPACE_ID'));
config.base_url ?? (config.base_url = readEnv('ANTHROPIC_BASE_URL'));
(_a = config.authentication).scope ?? (_a.scope = readEnv('ANTHROPIC_SCOPE'));
if (config.authentication.type === 'oidc_federation') {
if (!config.authentication.identity_token) {
const identityTokenFile = readEnv('ANTHROPIC_IDENTITY_TOKEN_FILE');
if (identityTokenFile) {
config.authentication.identity_token = {
source: 'file',
path: identityTokenFile,
};
}
}
// Unlike siblings using `??= readEnv()` (which leaves `undefined`), coerce
// to '' so the type stays `string` (always set). The downstream required
// check in credential-chain rejects empty, so semantics match but types are
// cleaner.
if (!config.authentication.federation_rule_id) {
config.authentication.federation_rule_id = readEnv('ANTHROPIC_FEDERATION_RULE_ID') ?? '';
}
(_b = config.authentication).service_account_id ?? (_b.service_account_id = readEnv('ANTHROPIC_SERVICE_ACCOUNT_ID'));
}
return { config, fromFile: true };
};
/**
* Loads the credential material for the active profile.
*
* Returns the parsed credentials or `null` when running in a browser or
* no credentials file can be found.
*
* **Profile resolution** (first match wins):
* 1. `ANTHROPIC_PROFILE` environment variable
* 2. Contents of `<config_dir>/active_config` file
* 3. `"default"`
*
* **Credentials path resolution** (first match wins):
* 1. `authentication.credentials_path` from the active profile's config (via {@link loadConfig})
* 2. `<config_dir>/credentials/<profile>.json`
*/
export const loadCredentials = async () => {
const config = await loadConfig();
const credentialsPath = await getCredentialsPath(config);
if (!credentialsPath) {
return null;
}
const fs = await import('node:fs');
let raw;
try {
raw = await fs.promises.readFile(credentialsPath, 'utf-8');
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read credentials file ${credentialsPath}: ${err}`);
}
return null;
}
let creds;
try {
creds = JSON.parse(raw);
}
catch (err) {
throw new Error(`failed to parse credentials file ${credentialsPath}: ${err}`);
}
if (creds.type && creds.type !== 'oauth_token') {
throw new Error(`credentials file ${credentialsPath} has unsupported type "${creds.type}" (want "oauth_token")`);
}
return creds;
};
/**
* Resolves the credentials file path for the given config.
*
* Uses `authentication.credentials_path` from the config if set, otherwise
* falls back to `<config_dir>/credentials/<profile>.json`.
*
* Returns `null` when running in a browser or the path cannot be resolved.
*/
export const getCredentialsPath = async (config, profile) => {
if (config?.authentication.credentials_path) {
return config.authentication.credentials_path;
}
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = profile ?? (await getActiveProfileName());
if (!profileName) {
return null;
}
validateProfileName(profileName);
const path = await import('node:path');
return path.join(rootConfigPath, 'credentials', `${profileName}.json`);
};
const getRootConfigPath = async () => {
if (!supportsLocalConfigFiles()) {
return null;
}
const path = await import('node:path');
// ANTHROPIC_CONFIG_DIR is treated as a trusted path: it is set by the
// process operator, not by remote input, so it is not validated.
const configDir = readEnv('ANTHROPIC_CONFIG_DIR');
if (configDir) {
return configDir;
}
const os = getPlatformHeaders()['X-Stainless-OS'];
if (os === 'Windows') {
const appData = readEnv('APPDATA');
if (appData) {
return path.join(appData, 'Anthropic');
}
const userProfile = readEnv('USERPROFILE');
if (userProfile) {
return path.join(userProfile, 'AppData', 'Roaming', 'Anthropic');
}
// No usable Windows config root — return null so callers fall through to
// "no config available" rather than silently writing under C:\.
return null;
}
const xdgConfigHome = readEnv('XDG_CONFIG_HOME');
if (xdgConfigHome) {
return path.join(xdgConfigHome, 'anthropic');
}
const home = readEnv('HOME');
if (home) {
return path.join(home, '.config', 'anthropic');
}
return null;
};
const supportsLocalConfigFiles = () => {
const runtime = getPlatformHeaders()['X-Stainless-Runtime'];
return runtime === 'node' || runtime === 'deno';
};
const getActiveProfileName = async () => {
const rootConfigPath = await getRootConfigPath();
if (!rootConfigPath) {
return null;
}
const profileName = readEnv('ANTHROPIC_PROFILE');
if (profileName) {
return profileName;
}
const fs = await import('node:fs');
const path = await import('node:path');
const filePath = path.join(rootConfigPath, 'active_config');
try {
return (await fs.promises.readFile(filePath, 'utf-8')).trim() || 'default';
}
catch (err) {
if (err?.code !== 'ENOENT') {
throw new Error(`failed to read ${filePath}: ${err}`);
}
return 'default';
}
};
//# sourceMappingURL=credentials.mjs.map
File diff suppressed because one or more lines are too long
+50
View File
@@ -0,0 +1,50 @@
import type { ErrorType } from "../resources/shared.mjs";
export declare class AnthropicError extends Error {
}
export declare class APIError<TStatus extends number | undefined = number | undefined, THeaders extends Headers | undefined = Headers | undefined, TError extends Object | undefined = Object | undefined> extends AnthropicError {
/** HTTP status for the response that caused the error */
readonly status: TStatus;
/** HTTP headers for the response that caused the error */
readonly headers: THeaders;
/** JSON body of the response that caused the error */
readonly error: TError;
readonly requestID: string | null | undefined;
/** The `error.type` from the API response body, e.g. `"rate_limit_error"` */
readonly type: ErrorType | null;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders, type?: ErrorType | null);
private static makeMessage;
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {
constructor({ message }?: {
message?: string;
});
}
export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {
constructor({ message, cause }: {
message?: string | undefined;
cause?: Error | undefined;
});
}
export declare class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message }?: {
message?: string;
});
}
export declare class BadRequestError extends APIError<400, Headers> {
}
export declare class AuthenticationError extends APIError<401, Headers> {
}
export declare class PermissionDeniedError extends APIError<403, Headers> {
}
export declare class NotFoundError extends APIError<404, Headers> {
}
export declare class ConflictError extends APIError<409, Headers> {
}
export declare class UnprocessableEntityError extends APIError<422, Headers> {
}
export declare class RateLimitError extends APIError<429, Headers> {
}
export declare class InternalServerError extends APIError<number, Headers> {
}
//# sourceMappingURL=error.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error.d.mts","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":"OAGO,KAAK,EAAE,SAAS,EAAE;AAEzB,qBAAa,cAAe,SAAQ,KAAK;CAAG;AAE5C,qBAAa,QAAQ,CACnB,OAAO,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,EACvD,QAAQ,SAAS,OAAO,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,EAC1D,MAAM,SAAS,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CACtD,SAAQ,cAAc;IACtB,yDAAyD;IACzD,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,0DAA0D;IAC1D,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;IAC3B,sDAAsD;IACtD,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAEvB,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAE9C,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,EAAE,SAAS,GAAG,IAAI,CAAC;gBAG9B,MAAM,EAAE,OAAO,EACf,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,GAA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,CAAC;CAAG;AAEvE,qBAAa,cAAe,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE7D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAAG"}
+50
View File
@@ -0,0 +1,50 @@
import type { ErrorType } from "../resources/shared.js";
export declare class AnthropicError extends Error {
}
export declare class APIError<TStatus extends number | undefined = number | undefined, THeaders extends Headers | undefined = Headers | undefined, TError extends Object | undefined = Object | undefined> extends AnthropicError {
/** HTTP status for the response that caused the error */
readonly status: TStatus;
/** HTTP headers for the response that caused the error */
readonly headers: THeaders;
/** JSON body of the response that caused the error */
readonly error: TError;
readonly requestID: string | null | undefined;
/** The `error.type` from the API response body, e.g. `"rate_limit_error"` */
readonly type: ErrorType | null;
constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders, type?: ErrorType | null);
private static makeMessage;
static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
}
export declare class APIUserAbortError extends APIError<undefined, undefined, undefined> {
constructor({ message }?: {
message?: string;
});
}
export declare class APIConnectionError extends APIError<undefined, undefined, undefined> {
constructor({ message, cause }: {
message?: string | undefined;
cause?: Error | undefined;
});
}
export declare class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message }?: {
message?: string;
});
}
export declare class BadRequestError extends APIError<400, Headers> {
}
export declare class AuthenticationError extends APIError<401, Headers> {
}
export declare class PermissionDeniedError extends APIError<403, Headers> {
}
export declare class NotFoundError extends APIError<404, Headers> {
}
export declare class ConflictError extends APIError<409, Headers> {
}
export declare class UnprocessableEntityError extends APIError<422, Headers> {
}
export declare class RateLimitError extends APIError<429, Headers> {
}
export declare class InternalServerError extends APIError<number, Headers> {
}
//# sourceMappingURL=error.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":"OAGO,KAAK,EAAE,SAAS,EAAE;AAE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AE,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;QAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAA;KAAE;CAM5F;AAED,qBAAa,yBAA0B,SAAQ,kBAAkB;gBACnD,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAO;CAGnD;AAED,qBAAa,eAAgB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE9D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAElE,qBAAa,qBAAsB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEpE,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,aAAc,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE5D,qBAAa,wBAAyB,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAEvE,qBAAa,cAAe,SAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CAAG;AAE7D,qBAAa,mBAAoB,SAAQ,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAAG"}
+116
View File
@@ -0,0 +1,116 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.AnthropicError = void 0;
const errors_1 = require("../internal/errors.js");
class AnthropicError extends Error {
}
exports.AnthropicError = AnthropicError;
class APIError extends AnthropicError {
constructor(status, error, message, headers, type) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get('request-id');
this.error = error;
this.type = type ?? null;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) {
return new APIConnectionError({ message, cause: (0, errors_1.castToError)(errorResponse) });
}
const error = errorResponse;
const type = error?.['error']?.['type'];
if (status === 400) {
return new BadRequestError(status, error, message, headers, type);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers, type);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers, type);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers, type);
}
if (status === 409) {
return new ConflictError(status, error, message, headers, type);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers, type);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers, type);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers, type);
}
return new APIError(status, error, message, headers, type);
}
}
exports.APIError = APIError;
class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
}
}
exports.APIUserAbortError = APIUserAbortError;
class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
exports.APIConnectionError = APIConnectionError;
class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
exports.APIConnectionTimeoutError = APIConnectionTimeoutError;
class BadRequestError extends APIError {
}
exports.BadRequestError = BadRequestError;
class AuthenticationError extends APIError {
}
exports.AuthenticationError = AuthenticationError;
class PermissionDeniedError extends APIError {
}
exports.PermissionDeniedError = PermissionDeniedError;
class NotFoundError extends APIError {
}
exports.NotFoundError = NotFoundError;
class ConflictError extends APIError {
}
exports.ConflictError = ConflictError;
class UnprocessableEntityError extends APIError {
}
exports.UnprocessableEntityError = UnprocessableEntityError;
class RateLimitError extends APIError {
}
exports.RateLimitError = RateLimitError;
class InternalServerError extends APIError {
}
exports.InternalServerError = InternalServerError;
//# sourceMappingURL=error.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error.js","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAEtF,kDAAiD;AAGjD,MAAa,cAAe,SAAQ,KAAK;CAAG;AAA5C,wCAA4C;AAE5C,MAAa,QAIX,SAAQ,cAAc;IAatB,YACE,MAAe,EACf,KAAa,EACb,OAA2B,EAC3B,OAAiB,EACjB,IAAuB;QAEvB,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,GAAG,CAAC,YAAY,CAAC,CAAC;QAC5C,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,IAAI,CAAC;IAC3B,CAAC;IAEO,MAAM,CAAC,WAAW,CAAC,MAA0B,EAAE,KAAU,EAAE,OAA2B;QAC5F,MAAM,GAAG,GACP,KAAK,EAAE,OAAO,CAAC,CAAC;YACd,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC;gBACjC,KAAK,CAAC,OAAO;gBACf,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC;YACjC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;gBAC/B,CAAC,CAAC,OAAO,CAAC;QAEZ,IAAI,MA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,yBAA0B,SAAQ,kBAAkB;IAC/D,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACtD,CAAC;CACF;AAJD,8DAIC;AAED,MAAa,eAAgB,SAAQ,QAAsB;CAAG;AAA9D,0CAA8D;AAE9D,MAAa,mBAAoB,SAAQ,QAAsB;CAAG;AAAlE,kDAAkE;AAElE,MAAa,qBAAsB,SAAQ,QAAsB;CAAG;AAApE,sDAAoE;AAEpE,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,aAAc,SAAQ,QAAsB;CAAG;AAA5D,sCAA4D;AAE5D,MAAa,wBAAyB,SAAQ,QAAsB;CAAG;AAAvE,4DAAuE;AAEvE,MAAa,cAAe,SAAQ,QAAsB;CAAG;AAA7D,wCAA6D;AAE7D,MAAa,mBAAoB,SAAQ,QAAyB;CAAG;AAArE,kDAAqE"}
+100
View File
@@ -0,0 +1,100 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { castToError } from "../internal/errors.mjs";
export class AnthropicError extends Error {
}
export class APIError extends AnthropicError {
constructor(status, error, message, headers, type) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
this.requestID = headers?.get('request-id');
this.error = error;
this.type = type ?? null;
}
static makeMessage(status, error, message) {
const msg = error?.message ?
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
if (status && msg) {
return `${status} ${msg}`;
}
if (status) {
return `${status} status code (no body)`;
}
if (msg) {
return msg;
}
return '(no status code or body)';
}
static generate(status, errorResponse, message, headers) {
if (!status || !headers) {
return new APIConnectionError({ message, cause: castToError(errorResponse) });
}
const error = errorResponse;
const type = error?.['error']?.['type'];
if (status === 400) {
return new BadRequestError(status, error, message, headers, type);
}
if (status === 401) {
return new AuthenticationError(status, error, message, headers, type);
}
if (status === 403) {
return new PermissionDeniedError(status, error, message, headers, type);
}
if (status === 404) {
return new NotFoundError(status, error, message, headers, type);
}
if (status === 409) {
return new ConflictError(status, error, message, headers, type);
}
if (status === 422) {
return new UnprocessableEntityError(status, error, message, headers, type);
}
if (status === 429) {
return new RateLimitError(status, error, message, headers, type);
}
if (status >= 500) {
return new InternalServerError(status, error, message, headers, type);
}
return new APIError(status, error, message, headers, type);
}
}
export class APIUserAbortError extends APIError {
constructor({ message } = {}) {
super(undefined, undefined, message || 'Request was aborted.', undefined);
}
}
export class APIConnectionError extends APIError {
constructor({ message, cause }) {
super(undefined, undefined, message || 'Connection error.', undefined);
// in some environments the 'cause' property is already declared
// @ts-ignore
if (cause)
this.cause = cause;
}
}
export class APIConnectionTimeoutError extends APIConnectionError {
constructor({ message } = {}) {
super({ message: message ?? 'Request timed out.' });
}
}
export class BadRequestError extends APIError {
}
export class AuthenticationError extends APIError {
}
export class PermissionDeniedError extends APIError {
}
export class NotFoundError extends APIError {
}
export class ConflictError extends APIError {
}
export class UnprocessableEntityError extends APIError {
}
export class RateLimitError extends APIError {
}
export class InternalServerError extends APIError {
}
//# sourceMappingURL=error.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"error.mjs","sourceRoot":"","sources":["../src/core/error.ts"],"names":[],"mappings":"AAAA,sFAAsF;OAE/E,EAAE,WAAW,EAAE;AAGtB,MAAM,OAAO,cAAe,SAAQ,KAAK;CAAG;AAE5C,MAAM,OAAO,QAIX,SAAQ,cAAc;IAatB,YACE,MAAe,EACf,KAAa,EACb,OAA2B,EAC3B,OAAiB,EACjB,IAAuB;QAEvB,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,OAAO,EAAE,GAAG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AAC;IAC7D,CAAC;CACF;AAED,MAAM,OAAO,iBAAkB,SAAQ,QAAyC;IAC9E,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAC5E,CAAC;CACF;AAED,MAAM,OAAO,kBAAmB,SAAQ,QAAyC;IAC/E,YAAY,EAAE,OAAO,EAAE,KAAK,EAA+D;QACzF,KAAK,CAAC,SAAS,EAAE,SAAS,EAAE,OAAO,IAAI,mBAAmB,EAAE,SAAS,CAAC,CAAC;QACvE,gEAAgE;QAChE,aAAa;QACb,IAAI,KAAK;YAAE,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IAChC,CAAC;CACF;AAED,MAAM,OAAO,yBAA0B,SAAQ,kBAAkB;IAC/D,YAAY,EAAE,OAAO,KAA2B,EAAE;QAChD,KAAK,CAAC,EAAE,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,CAAC,CAAC;IACtD,CAAC;CACF;AAED,MAAM,OAAO,eAAgB,SAAQ,QAAsB;CAAG;AAE9D,MAAM,OAAO,mBAAoB,SAAQ,QAAsB;CAAG;AAElE,MAAM,OAAO,qBAAsB,SAAQ,QAAsB;CAAG;AAEpE,MAAM,OAAO,aAAc,SAAQ,QAAsB;CAAG;AAE5D,MAAM,OAAO,aAAc,SAAQ,QAAsB;CAAG;AAE5D,MAAM,OAAO,wBAAyB,SAAQ,QAAsB;CAAG;AAEvE,MAAM,OAAO,cAAe,SAAQ,QAAsB;CAAG;AAE7D,MAAM,OAAO,mBAAoB,SAAQ,QAAyB;CAAG"}
+102
View File
@@ -0,0 +1,102 @@
import { FinalRequestOptions } from "../internal/request-options.mjs";
import { type BaseAnthropic } from "../client.mjs";
import { APIPromise } from "./api-promise.mjs";
import { type APIResponseProps } from "../internal/parse.mjs";
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: BaseAnthropic, response: Response, body: unknown, options: FinalRequestOptions);
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean;
getNextPage(): Promise<this>;
iterPages(): AsyncGenerator<this>;
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
constructor(client: BaseAnthropic, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
export interface PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
}
export interface PageParams {
/**
* Number of items per page.
*/
limit?: number;
before_id?: string;
after_id?: string;
}
export declare class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
}
export interface TokenPageParams {
/**
* Number of items per page.
*/
limit?: number;
page_token?: string;
}
export declare class TokenPage<Item> extends AbstractPage<Item> implements TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: TokenPageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
}
export interface PageCursorParams {
/**
* Number of items per page.
*/
limit?: number;
page?: string | null;
}
export declare class PageCursor<Item> extends AbstractPage<Item> implements PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageCursorResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
nextPageRequestOptions(): PageRequestOptions | null;
}
//# sourceMappingURL=pagination.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.mts","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"OAGO,EAAE,mBAAmB,EAAE;OAEvB,EAAE,KAAK,aAAa,EAAE;OACtB,EAAE,UAAU,EAAE;OACd,EAAE,KAAK,gBAAgB,EAAE;AAGhC,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,mBAAmB,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAC,CAAC;AAE7G,8BAAsB,YAAY,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAErE,SAAS,CAAC,OAAO,EAAE,mBAAmB,CAAC;IAEvC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,OAAO,CAAC;gBAEZ,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,mBAAmB;IAOlG,QAAQ,CAAC,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;IAE5D,QAAQ,CAAC,iBAAiB,IAAI,IAAI,EAAE;IAEpC,WAAW,IAAI,OAAO;IAMhB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAW3B,SAAS,IAAI,cA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AAQ,YAAY,CAAC,IAAI,CAAE,YAAW,kBAAkB,CAAC,IAAI,CAAC;IAC1F,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAC9B,OAAO,EAAE,mBAAmB;IAQ9B,iBAAiB,IAAI,IAAI,EAAE;IAI3B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD"}
+102
View File
@@ -0,0 +1,102 @@
import { FinalRequestOptions } from "../internal/request-options.js";
import { type BaseAnthropic } from "../client.js";
import { APIPromise } from "./api-promise.js";
import { type APIResponseProps } from "../internal/parse.js";
export type PageRequestOptions = Pick<FinalRequestOptions, 'query' | 'headers' | 'body' | 'path' | 'method'>;
export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
#private;
protected options: FinalRequestOptions;
protected response: Response;
protected body: unknown;
constructor(client: BaseAnthropic, response: Response, body: unknown, options: FinalRequestOptions);
abstract nextPageRequestOptions(): PageRequestOptions | null;
abstract getPaginatedItems(): Item[];
hasNextPage(): boolean;
getNextPage(): Promise<this>;
iterPages(): AsyncGenerator<this>;
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
constructor(client: BaseAnthropic, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
[Symbol.asyncIterator](): AsyncGenerator<Item>;
}
export interface PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
}
export interface PageParams {
/**
* Number of items per page.
*/
limit?: number;
before_id?: string;
after_id?: string;
}
export declare class Page<Item> extends AbstractPage<Item> implements PageResponse<Item> {
data: Array<Item>;
has_more: boolean;
first_id: string | null;
last_id: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
}
export interface TokenPageParams {
/**
* Number of items per page.
*/
limit?: number;
page_token?: string;
}
export declare class TokenPage<Item> extends AbstractPage<Item> implements TokenPageResponse<Item> {
data: Array<Item>;
has_more: boolean;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: TokenPageResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
hasNextPage(): boolean;
nextPageRequestOptions(): PageRequestOptions | null;
}
export interface PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
}
export interface PageCursorParams {
/**
* Number of items per page.
*/
limit?: number;
page?: string | null;
}
export declare class PageCursor<Item> extends AbstractPage<Item> implements PageCursorResponse<Item> {
data: Array<Item>;
next_page: string | null;
constructor(client: BaseAnthropic, response: Response, body: PageCursorResponse<Item>, options: FinalRequestOptions);
getPaginatedItems(): Item[];
nextPageRequestOptions(): PageRequestOptions | null;
}
//# sourceMappingURL=pagination.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pagination.d.ts","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"OAGO,EAAE,mBAAmB,EAAE;OAEvB,EAAE,KAAK,aAAa,EAAE;OACtB,EAAE,UAAU,EAAE;OACd,EAAE,KAAK,gBAAgB,EAAE;AAGhC,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,mBAAmB,EAAE,OAAO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AE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,iBAAiB,CAAC,IAAI,CAAC,EAC7B,OAAO,EAAE,mBAAmB;IAS9B,iBAAiB,IAAI,IAAI,EAAE;IAIlB,WAAW,IAAI,OAAO;IAQ/B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD;AAED,MAAM,WAAW,kBAAkB,CAAC,IAAI;IACtC,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED,qBAAa,UAAU,CAAC,IAAI,CAAE,SAAQ,YAAY,CAAC,IAAI,CAAE,YAAW,kBAAkB,CAAC,IAAI,CAAC;IAC1F,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC;IAElB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;gBAGvB,MAAM,EAAE,aAAa,EACrB,QAAQ,EAAE,QAAQ,EAClB,IAAI,EAAE,kBAAkB,CAAC,IAAI,CAAC,EAC9B,OAAO,EAAE,mBAAmB;IAQ9B,iBAAiB,IAAI,IAAI,EAAE;IAI3B,sBAAsB,IAAI,kBAAkB,GAAG,IAAI;CAcpD"}
+178
View File
@@ -0,0 +1,178 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PageCursor = exports.TokenPage = exports.Page = exports.PagePromise = exports.AbstractPage = void 0;
const tslib_1 = require("../internal/tslib.js");
const error_1 = require("./error.js");
const parse_1 = require("../internal/parse.js");
const api_promise_1 = require("./api-promise.js");
const values_1 = require("../internal/utils/values.js");
class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
tslib_1.__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new error_1.AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await tslib_1.__classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
exports.AbstractPage = AbstractPage;
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
class PagePromise extends api_promise_1.APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await (0, parse_1.defaultParseResponse)(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
exports.PagePromise = PagePromise;
class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
after_id: cursor,
},
};
}
}
exports.Page = Page;
class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
page_token: cursor,
},
};
}
}
exports.TokenPage = TokenPage;
class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...(0, values_1.maybeObj)(this.options.query),
page: cursor,
},
};
}
}
exports.PageCursor = PageCursor;
//# sourceMappingURL=pagination.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pagination.js","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;;;AAEtF,sCAAyC;AAEzC,gDAAwE;AAExE,kDAA2C;AAE3C,wDAAoD;AAIpD,MAAsB,YAAY;IAOhC,YAAY,MAAqB,EAAE,QAAkB,EAAE,IAAa,EAAE,OAA4B;QANlG,uCAAuB;QAOrB,+BAAA,IAAI,wBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAMD,WAAW;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvC,IAAI,CAAC,KAAK,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AO;YACf,KAAK,EAAE;gBACL,GAAG,IAAA,iBAAQ,EAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,UAAU,EAAE,MAAM;aACnB;SACF,CAAC;IACJ,CAAC;CACF;AA9CD,8BA8CC;AAiBD,MAAa,UAAiB,SAAQ,YAAkB;IAKtD,YACE,MAAqB,EACrB,QAAkB,EAClB,IAA8B,EAC9B,OAA4B;QAE5B,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;IAC1C,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,sBAAsB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;QAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,GAAG,IAAI,CAAC,OAAO;YACf,KAAK,EAAE;gBACL,GAAG,IAAA,iBAAQ,EAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,IAAI,EAAE,MAAM;aACb;SACF,CAAC;IACJ,CAAC;CACF;AAnCD,gCAmCC"}
+170
View File
@@ -0,0 +1,170 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
var _AbstractPage_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { defaultParseResponse } from "../internal/parse.mjs";
import { APIPromise } from "./api-promise.mjs";
import { maybeObj } from "../internal/utils/values.mjs";
export class AbstractPage {
constructor(client, response, body, options) {
_AbstractPage_client.set(this, void 0);
__classPrivateFieldSet(this, _AbstractPage_client, client, "f");
this.options = options;
this.response = response;
this.body = body;
}
hasNextPage() {
const items = this.getPaginatedItems();
if (!items.length)
return false;
return this.nextPageRequestOptions() != null;
}
async getNextPage() {
const nextOptions = this.nextPageRequestOptions();
if (!nextOptions) {
throw new AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');
}
return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions);
}
async *iterPages() {
let page = this;
yield page;
while (page.hasNextPage()) {
page = await page.getNextPage();
yield page;
}
}
async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {
for await (const page of this.iterPages()) {
for (const item of page.getPaginatedItems()) {
yield item;
}
}
}
}
/**
* This subclass of Promise will resolve to an instantiated Page once the request completes.
*
* It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
export class PagePromise extends APIPromise {
constructor(client, request, Page) {
super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options));
}
/**
* Allow auto-paginating iteration on an unawaited list call, eg:
*
* for await (const item of client.items.list()) {
* console.log(item)
* }
*/
async *[Symbol.asyncIterator]() {
const page = await this;
for await (const item of page) {
yield item;
}
}
}
export class Page extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.first_id = body.first_id || null;
this.last_id = body.last_id || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
if (this.options.query?.['before_id']) {
// in reverse
const first_id = this.first_id;
if (!first_id) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
before_id: first_id,
},
};
}
const cursor = this.last_id;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
after_id: cursor,
},
};
}
}
export class TokenPage extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.has_more = body.has_more || false;
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
hasNextPage() {
if (this.has_more === false) {
return false;
}
return super.hasNextPage();
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page_token: cursor,
},
};
}
}
export class PageCursor extends AbstractPage {
constructor(client, response, body, options) {
super(client, response, body, options);
this.data = body.data || [];
this.next_page = body.next_page || null;
}
getPaginatedItems() {
return this.data ?? [];
}
nextPageRequestOptions() {
const cursor = this.next_page;
if (!cursor) {
return null;
}
return {
...this.options,
query: {
...maybeObj(this.options.query),
page: cursor,
},
};
}
}
//# sourceMappingURL=pagination.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"pagination.mjs","sourceRoot":"","sources":["../src/core/pagination.ts"],"names":[],"mappings":"AAAA,sFAAsF;;;OAE/E,EAAE,cAAc,EAAE;OAElB,EAAE,oBAAoB,EAAiB;OAEvC,EAAE,UAAU,EAAE;OAEd,EAAE,QAAQ,EAAE;AAInB,MAAM,OAAgB,YAAY;IAOhC,YAAY,MAAqB,EAAE,QAAkB,EAAE,IAAa,EAAE,OAA4B;QANlG,uCAAuB;QAOrB,uBAAA,IAAI,wBAAW,MAAM,MAAA,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAMD,WAAW;QACT,MAAM,KAAK,GAAG,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACvC,IAAI,CAAC,KAAK,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAChC,OAAO,IAAI,CAAC,sBAAsB,EAAE,IAAI,IAAI,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,WAAW;QACf,MAAM,WAAW,GAAG,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAClD,IAAI,CAAC,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AK,CAAC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAEvC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC;IAC1C,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC,IAAI,IAAI,EAAE,CAAC;IACzB,CAAC;IAED,sBAAsB;QACpB,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC;QAC9B,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO;YACL,GAAG,IAAI,CAAC,OAAO;YACf,KAAK,EAAE;gBACL,GAAG,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;gBAC/B,IAAI,EAAE,MAAM;aACb;SACF,CAAC;IACJ,CAAC;CACF"}
+6
View File
@@ -0,0 +1,6 @@
import { BaseAnthropic } from "../client.mjs";
export declare abstract class APIResource {
protected _client: BaseAnthropic;
constructor(client: BaseAnthropic);
}
//# sourceMappingURL=resource.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"resource.d.mts","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"OAEO,EAAE,aAAa,EAAE;AAExB,8BAAsB,WAAW;IAC/B,SAAS,CAAC,OAAO,EAAE,aAAa,CAAC;gBAErB,MAAM,EAAE,aAAa;CAGlC"}
+6
View File
@@ -0,0 +1,6 @@
import { BaseAnthropic } from "../client.js";
export declare abstract class APIResource {
protected _client: BaseAnthropic;
constructor(client: BaseAnthropic);
}
//# sourceMappingURL=resource.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"resource.d.ts","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"OAEO,EAAE,aAAa,EAAE;AAExB,8BAAsB,WAAW;IAC/B,SAAS,CAAC,OAAO,EAAE,aAAa,CAAC;gBAErB,MAAM,EAAE,aAAa;CAGlC"}
+11
View File
@@ -0,0 +1,11 @@
"use strict";
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIResource = void 0;
class APIResource {
constructor(client) {
this._client = client;
}
}
exports.APIResource = APIResource;
//# sourceMappingURL=resource.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"resource.js","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":";AAAA,sFAAsF;;;AAItF,MAAsB,WAAW;IAG/B,YAAY,MAAqB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF;AAND,kCAMC"}
+7
View File
@@ -0,0 +1,7 @@
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
export class APIResource {
constructor(client) {
this._client = client;
}
}
//# sourceMappingURL=resource.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"resource.mjs","sourceRoot":"","sources":["../src/core/resource.ts"],"names":[],"mappings":"AAAA,sFAAsF;AAItF,MAAM,OAAgB,WAAW;IAG/B,YAAY,MAAqB;QAC/B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IACxB,CAAC;CACF"}
+33
View File
@@ -0,0 +1,33 @@
import { type ReadableStream } from "../internal/shim-types.mjs";
import type { BaseAnthropic } from "../client.mjs";
export type ServerSentEvent = {
event: string | null;
data: string;
raw: string[];
};
export declare class Stream<Item> implements AsyncIterable<Item> {
#private;
private iterator;
controller: AbortController;
constructor(iterator: () => AsyncIterator<Item>, controller: AbortController, client?: BaseAnthropic);
static fromSSEResponse<Item>(response: Response, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
[Symbol.asyncIterator](): AsyncIterator<Item>;
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee(): [Stream<Item>, Stream<Item>];
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream(): ReadableStream;
}
export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator<ServerSentEvent, void, unknown>;
//# sourceMappingURL=streaming.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"streaming.d.mts","sourceRoot":"","sources":["../src/core/streaming.ts"],"names":[],"mappings":"OACO,EAAE,KAAK,cAAc,EAAE;OAQvB,KAAK,EAAE,aAAa,EAAE;AAO7B,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACf,CAAC;AAEF,qBAAa,MAAM,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAKpD,OAAO,CAAC,QAAQ;IAJlB,UAAU,EAAE,eAAe,CAAC;gBAIlB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,EAC3C,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa;IAMxB,MAAM,CAAC,eAAe,CAAC,IAAI,EACzB,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IAkGf;;;OAGG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAC5B,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IA2Cf,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC;IAI7C;;;OAGG;IACH,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAwBnC;;;;OAIG;IACH,gBAAgB,IAAI,cAAc;CAyBnC;AAED,wBAAuB,gBAAgB,CACrC,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,GAC1B,cAAc,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,CAAC,CA6BhD"}
+33
View File
@@ -0,0 +1,33 @@
import { type ReadableStream } from "../internal/shim-types.js";
import type { BaseAnthropic } from "../client.js";
export type ServerSentEvent = {
event: string | null;
data: string;
raw: string[];
};
export declare class Stream<Item> implements AsyncIterable<Item> {
#private;
private iterator;
controller: AbortController;
constructor(iterator: () => AsyncIterator<Item>, controller: AbortController, client?: BaseAnthropic);
static fromSSEResponse<Item>(response: Response, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream<Item>(readableStream: ReadableStream, controller: AbortController, client?: BaseAnthropic): Stream<Item>;
[Symbol.asyncIterator](): AsyncIterator<Item>;
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee(): [Stream<Item>, Stream<Item>];
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream(): ReadableStream;
}
export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator<ServerSentEvent, void, unknown>;
//# sourceMappingURL=streaming.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"streaming.d.ts","sourceRoot":"","sources":["../src/core/streaming.ts"],"names":[],"mappings":"OACO,EAAE,KAAK,cAAc,EAAE;OAQvB,KAAK,EAAE,aAAa,EAAE;AAO7B,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,EAAE,CAAC;CACf,CAAC;AAEF,qBAAa,MAAM,CAAC,IAAI,CAAE,YAAW,aAAa,CAAC,IAAI,CAAC;;IAKpD,OAAO,CAAC,QAAQ;IAJlB,UAAU,EAAE,eAAe,CAAC;gBAIlB,QAAQ,EAAE,MAAM,aAAa,CAAC,IAAI,CAAC,EAC3C,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa;IAMxB,MAAM,CAAC,eAAe,CAAC,IAAI,EACzB,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IAkGf;;;OAGG;IACH,MAAM,CAAC,kBAAkB,CAAC,IAAI,EAC5B,cAAc,EAAE,cAAc,EAC9B,UAAU,EAAE,eAAe,EAC3B,MAAM,CAAC,EAAE,aAAa,GACrB,MAAM,CAAC,IAAI,CAAC;IA2Cf,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,IAAI,CAAC;IAI7C;;;OAGG;IACH,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAwBnC;;;;OAIG;IACH,gBAAgB,IAAI,cAAc;CAyBnC;AAED,wBAAuB,gBAAgB,CACrC,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,eAAe,GAC1B,cAAc,CAAC,eAAe,EAAE,IAAI,EAAE,OAAO,CAAC,CA6BhD"}
+325
View File
@@ -0,0 +1,325 @@
"use strict";
var _Stream_client;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Stream = void 0;
exports._iterSSEMessages = _iterSSEMessages;
const tslib_1 = require("../internal/tslib.js");
const error_1 = require("./error.js");
const shims_1 = require("../internal/shims.js");
const line_1 = require("../internal/decoders/line.js");
const shims_2 = require("../internal/shims.js");
const errors_1 = require("../internal/errors.js");
const values_1 = require("../internal/utils/values.js");
const bytes_1 = require("../internal/utils/bytes.js");
const log_1 = require("../internal/utils/log.js");
const error_2 = require("./error.js");
class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
tslib_1.__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? (0, log_1.loggerFor)(client) : console;
async function* iterator() {
if (consumed) {
throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop' ||
sse.event === 'message' ||
sse.event === 'user.message' ||
sse.event === 'user.interrupt' ||
sse.event === 'user.tool_confirmation' ||
sse.event === 'user.custom_tool_result' ||
sse.event === 'agent.message' ||
sse.event === 'agent.thinking' ||
sse.event === 'agent.tool_use' ||
sse.event === 'agent.tool_result' ||
sse.event === 'agent.mcp_tool_use' ||
sse.event === 'agent.mcp_tool_result' ||
sse.event === 'agent.custom_tool_use' ||
sse.event === 'agent.thread_context_compacted' ||
sse.event === 'session.status_running' ||
sse.event === 'session.status_idle' ||
sse.event === 'session.status_rescheduled' ||
sse.event === 'session.status_terminated' ||
sse.event === 'session.error' ||
sse.event === 'session.deleted' ||
sse.event === 'span.model_request_start' ||
sse.event === 'span.model_request_end' ||
sse.event === 'span.outcome_evaluation_start' ||
sse.event === 'span.outcome_evaluation_ongoing' ||
sse.event === 'span.outcome_evaluation_end' ||
sse.event === 'user.define_outcome' ||
sse.event === 'agent.thread_message_received' ||
sse.event === 'agent.thread_message_sent' ||
sse.event === 'agent.session_thread_message_received' ||
sse.event === 'agent.session_thread_message_sent' ||
sse.event === 'session.thread_created' ||
sse.event === 'session.thread_status_created' ||
sse.event === 'session.thread_status_running' ||
sse.event === 'session.thread_status_idle' ||
sse.event === 'session.thread_status_rescheduled' ||
sse.event === 'session.thread_status_terminated') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
const body = (0, values_1.safeJSON)(sse.data) ?? sse.data;
const type = body?.error?.type;
throw new error_2.APIError(undefined, body, undefined, response.headers, type);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if ((0, errors_1.isAbortError)(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new line_1.LineDecoder();
const iter = (0, shims_2.ReadableStreamToAsyncIterable)(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if ((0, errors_1.isAbortError)(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return (0, shims_1.makeReadableStream)({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = (0, bytes_1.encodeUTF8)(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
exports.Stream = Stream;
async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new error_1.AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new error_1.AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new line_1.LineDecoder();
const iter = (0, shims_2.ReadableStreamToAsyncIterable)(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? (0, bytes_1.encodeUTF8)(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = (0, line_1.findDoubleNewlineIndex)(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.js.map
File diff suppressed because one or more lines are too long
+320
View File
@@ -0,0 +1,320 @@
var _Stream_client;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "../internal/tslib.mjs";
import { AnthropicError } from "./error.mjs";
import { makeReadableStream } from "../internal/shims.mjs";
import { findDoubleNewlineIndex, LineDecoder } from "../internal/decoders/line.mjs";
import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs";
import { isAbortError } from "../internal/errors.mjs";
import { safeJSON } from "../internal/utils/values.mjs";
import { encodeUTF8 } from "../internal/utils/bytes.mjs";
import { loggerFor } from "../internal/utils/log.mjs";
import { APIError } from "./error.mjs";
export class Stream {
constructor(iterator, controller, client) {
this.iterator = iterator;
_Stream_client.set(this, void 0);
this.controller = controller;
__classPrivateFieldSet(this, _Stream_client, client, "f");
}
static fromSSEResponse(response, controller, client) {
let consumed = false;
const logger = client ? loggerFor(client) : console;
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const sse of _iterSSEMessages(response, controller)) {
if (sse.event === 'completion') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'message_start' ||
sse.event === 'message_delta' ||
sse.event === 'message_stop' ||
sse.event === 'content_block_start' ||
sse.event === 'content_block_delta' ||
sse.event === 'content_block_stop' ||
sse.event === 'message' ||
sse.event === 'user.message' ||
sse.event === 'user.interrupt' ||
sse.event === 'user.tool_confirmation' ||
sse.event === 'user.custom_tool_result' ||
sse.event === 'agent.message' ||
sse.event === 'agent.thinking' ||
sse.event === 'agent.tool_use' ||
sse.event === 'agent.tool_result' ||
sse.event === 'agent.mcp_tool_use' ||
sse.event === 'agent.mcp_tool_result' ||
sse.event === 'agent.custom_tool_use' ||
sse.event === 'agent.thread_context_compacted' ||
sse.event === 'session.status_running' ||
sse.event === 'session.status_idle' ||
sse.event === 'session.status_rescheduled' ||
sse.event === 'session.status_terminated' ||
sse.event === 'session.error' ||
sse.event === 'session.deleted' ||
sse.event === 'span.model_request_start' ||
sse.event === 'span.model_request_end' ||
sse.event === 'span.outcome_evaluation_start' ||
sse.event === 'span.outcome_evaluation_ongoing' ||
sse.event === 'span.outcome_evaluation_end' ||
sse.event === 'user.define_outcome' ||
sse.event === 'agent.thread_message_received' ||
sse.event === 'agent.thread_message_sent' ||
sse.event === 'agent.session_thread_message_received' ||
sse.event === 'agent.session_thread_message_sent' ||
sse.event === 'session.thread_created' ||
sse.event === 'session.thread_status_created' ||
sse.event === 'session.thread_status_running' ||
sse.event === 'session.thread_status_idle' ||
sse.event === 'session.thread_status_rescheduled' ||
sse.event === 'session.thread_status_terminated') {
try {
yield JSON.parse(sse.data);
}
catch (e) {
logger.error(`Could not parse message into JSON:`, sse.data);
logger.error(`From chunk:`, sse.raw);
throw e;
}
}
if (sse.event === 'ping') {
continue;
}
if (sse.event === 'error') {
const body = safeJSON(sse.data) ?? sse.data;
const type = body?.error?.type;
throw new APIError(undefined, body, undefined, response.headers, type);
}
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
/**
* Generates a Stream from a newline-separated ReadableStream
* where each item is a JSON value.
*/
static fromReadableStream(readableStream, controller, client) {
let consumed = false;
async function* iterLines() {
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(readableStream);
for await (const chunk of iter) {
for (const line of lineDecoder.decode(chunk)) {
yield line;
}
}
for (const line of lineDecoder.flush()) {
yield line;
}
}
async function* iterator() {
if (consumed) {
throw new AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
}
consumed = true;
let done = false;
try {
for await (const line of iterLines()) {
if (done)
continue;
if (line)
yield JSON.parse(line);
}
done = true;
}
catch (e) {
// If the user calls `stream.controller.abort()`, we should exit without throwing.
if (isAbortError(e))
return;
throw e;
}
finally {
// If the user `break`s, abort the ongoing request.
if (!done)
controller.abort();
}
}
return new Stream(iterator, controller, client);
}
[(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() {
return this.iterator();
}
/**
* Splits the stream into two streams which can be
* independently read from at different speeds.
*/
tee() {
const left = [];
const right = [];
const iterator = this.iterator();
const teeIterator = (queue) => {
return {
next: () => {
if (queue.length === 0) {
const result = iterator.next();
left.push(result);
right.push(result);
}
return queue.shift();
},
};
};
return [
new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")),
];
}
/**
* Converts this stream to a newline-separated ReadableStream of
* JSON stringified values in the stream
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
*/
toReadableStream() {
const self = this;
let iter;
return makeReadableStream({
async start() {
iter = self[Symbol.asyncIterator]();
},
async pull(ctrl) {
try {
const { value, done } = await iter.next();
if (done)
return ctrl.close();
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
ctrl.enqueue(bytes);
}
catch (err) {
ctrl.error(err);
}
},
async cancel() {
await iter.return?.();
},
});
}
}
export async function* _iterSSEMessages(response, controller) {
if (!response.body) {
controller.abort();
if (typeof globalThis.navigator !== 'undefined' &&
globalThis.navigator.product === 'ReactNative') {
throw new AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
}
throw new AnthropicError(`Attempted to iterate over a response with no body`);
}
const sseDecoder = new SSEDecoder();
const lineDecoder = new LineDecoder();
const iter = ReadableStreamToAsyncIterable(response.body);
for await (const sseChunk of iterSSEChunks(iter)) {
for (const line of lineDecoder.decode(sseChunk)) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
for (const line of lineDecoder.flush()) {
const sse = sseDecoder.decode(line);
if (sse)
yield sse;
}
}
/**
* Given an async iterable iterator, iterates over it and yields full
* SSE chunks, i.e. yields when a double new-line is encountered.
*/
async function* iterSSEChunks(iterator) {
let data = new Uint8Array();
for await (const chunk of iterator) {
if (chunk == null) {
continue;
}
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
: typeof chunk === 'string' ? encodeUTF8(chunk)
: chunk;
let newData = new Uint8Array(data.length + binaryChunk.length);
newData.set(data);
newData.set(binaryChunk, data.length);
data = newData;
let patternIndex;
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
yield data.slice(0, patternIndex);
data = data.slice(patternIndex);
}
}
if (data.length > 0) {
yield data;
}
}
class SSEDecoder {
constructor() {
this.event = null;
this.data = [];
this.chunks = [];
}
decode(line) {
if (line.endsWith('\r')) {
line = line.substring(0, line.length - 1);
}
if (!line) {
// empty line and we didn't previously encounter any messages
if (!this.event && !this.data.length)
return null;
const sse = {
event: this.event,
data: this.data.join('\n'),
raw: this.chunks,
};
this.event = null;
this.data = [];
this.chunks = [];
return sse;
}
this.chunks.push(line);
if (line.startsWith(':')) {
return null;
}
let [fieldname, _, value] = partition(line, ':');
if (value.startsWith(' ')) {
value = value.substring(1);
}
if (fieldname === 'event') {
this.event = value;
}
else if (fieldname === 'data') {
this.data.push(value);
}
return null;
}
}
function partition(str, delimiter) {
const index = str.indexOf(delimiter);
if (index !== -1) {
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
}
return [str, '', ''];
}
//# sourceMappingURL=streaming.mjs.map
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
export { type Uploadable } from "../internal/uploads.mjs";
export { toFile, type ToFileInput } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.d.mts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uploads.d.mts","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,UAAU,EAAE;OACnB,EAAE,MAAM,EAAE,KAAK,WAAW,EAAE"}
+3
View File
@@ -0,0 +1,3 @@
export { type Uploadable } from "../internal/uploads.js";
export { toFile, type ToFileInput } from "../internal/to-file.js";
//# sourceMappingURL=uploads.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uploads.d.ts","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OAAO,EAAE,KAAK,UAAU,EAAE;OACnB,EAAE,MAAM,EAAE,KAAK,WAAW,EAAE"}
+6
View File
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toFile = void 0;
var to_file_1 = require("../internal/to-file.js");
Object.defineProperty(exports, "toFile", { enumerable: true, get: function () { return to_file_1.toFile; } });
//# sourceMappingURL=uploads.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uploads.js","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":";;;AACA,kDAA+D;AAAtD,iGAAA,MAAM,OAAA"}
+2
View File
@@ -0,0 +1,2 @@
export { toFile } from "../internal/to-file.mjs";
//# sourceMappingURL=uploads.mjs.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"uploads.mjs","sourceRoot":"","sources":["../src/core/uploads.ts"],"names":[],"mappings":"OACO,EAAE,MAAM,EAAoB"}