@atproto/lex-client 0.0.15 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @atproto/lex-client
2
2
 
3
+ ## 0.0.16
4
+
5
+ ### Patch Changes
6
+
7
+ - [#4714](https://github.com/bluesky-social/atproto/pull/4714) [`5a2f884`](https://github.com/bluesky-social/atproto/commit/5a2f8847efd91252971fa243d21bd52ada7aa8f4) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Create a specific error class for wrapping unexpected error returned by the `fetchHandler`. This allows to better distinguish unexpected internal server errors (due to implementation encountering an unexpected case) from potentially transient errors that occur when performing network HTTP requests.
8
+
9
+ - Updated dependencies [[`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe), [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe), [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe), [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe), [`112b159`](https://github.com/bluesky-social/atproto/commit/112b159ec293a5c3fff41237474a3788fc47f9ca), [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe), [`3dc3791`](https://github.com/bluesky-social/atproto/commit/3dc37915436dec7e18c7dc9dcf01b72cad53fdbe)]:
10
+ - @atproto/lex-schema@0.0.15
11
+
3
12
  ## 0.0.15
4
13
 
5
14
  ### Patch Changes
package/dist/agent.d.ts CHANGED
@@ -81,7 +81,7 @@ export type AgentConfig = {
81
81
  *
82
82
  * Can be a full {@link AgentConfig} object, or a simple service URL string/{@link URL}.
83
83
  */
84
- export type AgentOptions = AgentConfig | string | URL;
84
+ export type AgentOptions = AgentConfig | FetchHandler | string | URL;
85
85
  /**
86
86
  * Creates an {@link Agent} from various input types.
87
87
  *
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,YAAY,GAAG;AACzB;;;;GAIG;AACH,IAAI,EAAE,IAAI,MAAM,EAAE,EAClB,IAAI,EAAE,WAAW,KACd,OAAO,CAAC,QAAQ,CAAC,CAAA;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,KAAK;IACpB,4EAA4E;IAC5E,QAAQ,CAAC,GAAG,CAAC,EAAE,SAAS,CAAA;IACxB,oDAAoD;IACpD,YAAY,EAAE,YAAY,CAAA;CAC3B;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,KAAK,CAUtD;AAED,MAAM,MAAM,WAAW,GAAG;IACxB;;OAEG;IACH,GAAG,CAAC,EAAE,SAAS,CAAA;IAEf;;;;OAIG;IACH,OAAO,EAAE,MAAM,GAAG,GAAG,CAAA;IAErB;;;OAGG;IACH,OAAO,CAAC,EAAE,WAAW,CAAA;IAErB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;CAChC,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,MAAM,GAAG,GAAG,CAAA;AAErD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,KAAK,GAAG,YAAY,EACvD,OAAO,EAAE,CAAC,GACT,CAAC,SAAS,KAAK,GAAG,CAAC,GAAG,KAAK,CAAA"}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C;;;;;;;;;;;GAWG;AACH,MAAM,MAAM,YAAY,GAAG;AACzB;;;;GAIG;AACH,IAAI,EAAE,IAAI,MAAM,EAAE,EAClB,IAAI,EAAE,WAAW,KACd,OAAO,CAAC,QAAQ,CAAC,CAAA;AAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,KAAK;IACpB,4EAA4E;IAC5E,QAAQ,CAAC,GAAG,CAAC,EAAE,SAAS,CAAA;IACxB,oDAAoD;IACpD,YAAY,EAAE,YAAY,CAAA;CAC3B;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,KAAK,CAUtD;AAED,MAAM,MAAM,WAAW,GAAG;IACxB;;OAEG;IACH,GAAG,CAAC,EAAE,SAAS,CAAA;IAEf;;;;OAIG;IACH,OAAO,EAAE,MAAM,GAAG,GAAG,CAAA;IAErB;;;OAGG;IACH,OAAO,CAAC,EAAE,WAAW,CAAA;IAErB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;CAChC,CAAA;AAED;;;;GAIG;AACH,MAAM,MAAM,YAAY,GAAG,WAAW,GAAG,YAAY,GAAG,MAAM,GAAG,GAAG,CAAA;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,KAAK,GAAG,YAAY,EACvD,OAAO,EAAE,CAAC,GACT,CAAC,SAAS,KAAK,GAAG,CAAC,GAAG,KAAK,CAAA"}
package/dist/agent.js CHANGED
@@ -12,11 +12,13 @@ function isAgent(value) {
12
12
  typeof value.did === 'string'));
13
13
  }
14
14
  function buildAgent(options) {
15
- if (isAgent(options))
16
- return options;
17
- const config = typeof options === 'string' || options instanceof URL
18
- ? { did: undefined, service: options }
19
- : options;
15
+ const config = typeof options === 'function'
16
+ ? { did: undefined, fetchHandler: options }
17
+ : typeof options === 'string' || options instanceof URL
18
+ ? { did: undefined, service: options }
19
+ : options;
20
+ if (isAgent(config))
21
+ return config;
20
22
  const { service, fetch = globalThis.fetch } = config;
21
23
  if (typeof fetch !== 'function') {
22
24
  throw new TypeError('fetch() is not available in this environment');
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;AA0DA,0BAUC;AAiED,gCA+BC;AA1GD,SAAgB,OAAO,CAAC,KAAc;IACpC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,cAAc,IAAI,KAAK;QACvB,OAAO,KAAK,CAAC,YAAY,KAAK,UAAU;QACxC,CAAC,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC;YAChB,KAAK,CAAC,GAAG,KAAK,SAAS;YACvB,OAAO,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,CACjC,CAAA;AACH,CAAC;AAiED,SAAgB,UAAU,CAAC,OAA6B;IACtD,IAAI,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,OAAO,CAAA;IAEpC,MAAM,MAAM,GACV,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,YAAY,GAAG;QACnD,CAAC,CAAC,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE;QACtC,CAAC,CAAC,OAAO,CAAA;IAEb,MAAM,EAAE,OAAO,EAAE,KAAK,GAAG,UAAU,CAAC,KAAK,EAAE,GAAG,MAAM,CAAA;IAEpD,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CAAC,8CAA8C,CAAC,CAAA;IACrE,CAAC;IAED,OAAO;QACL,IAAI,GAAG;YACL,OAAO,MAAM,CAAC,GAAG,CAAA;QACnB,CAAC;QAED,KAAK,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI;YAC3B,MAAM,OAAO,GACX,MAAM,CAAC,OAAO,IAAI,IAAI,IAAI,IAAI,CAAC,OAAO,IAAI,IAAI;gBAC5C,CAAC,CAAC,YAAY,CAAC,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC;gBAC5C,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAA;YAEpC,OAAO,KAAK,CACV,IAAI,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,EACtB,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CACvD,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC;AAED,SAAS,YAAY,CACnB,cAA2B,EAC3B,cAA2B;IAE3B,8EAA8E;IAC9E,MAAM,MAAM,GAAG,IAAI,OAAO,CAAC,cAAc,CAAC,CAAA;IAE1C,MAAM,SAAS,GACb,cAAc,YAAY,OAAO;QAC/B,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,IAAI,OAAO,CAAC,cAAc,CAAC,CAAA;IAEjC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,EAAE,EAAE,CAAC;QAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACxB,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { DidString } from '@atproto/lex-schema'\n\n/**\n * A function that performs HTTP requests towards a service endpoint.\n *\n * The handler is responsible for adding the origin (protocol, hostname, and\n * port) to the provided path, typically based on authentication or service\n * configuration. The handler can also be responsible for adding any necessary\n * headers, such as authorization tokens.\n *\n * @param path - The URL path (pathname + query parameters) without the origin\n * @param init - Standard fetch RequestInit options\n * @returns A Promise resolving to the HTTP Response\n */\nexport type FetchHandler = (\n /**\n * The URL (pathname + query parameters) to make the request to, without the\n * origin. The origin (protocol, hostname, and port) must be added by this\n * {@link FetchHandler}, typically based on authentication or other factors.\n */\n path: `/${string}`,\n init: RequestInit,\n) => Promise<Response>\n\n/**\n * Core interface for making XRPC requests towards a specific service.\n *\n * An {@link Agent} encapsulates an identity and request handling for AT\n * Protocol operations. Agents will typically handle authentication, service URL\n * resolution, and other request configuration, allowing client code to make\n * requests without needing to manage these details directly. The key component\n * of an Agent is the {@link FetchHandler}, which is responsible for\n * constructing the full request URL and adding any necessary headers or\n * authentication tokens. The Agent's `did` property represents the\n * authenticated user's DID, if available, and can be used for operations that\n * require knowledge of the user's identity (such as creating AT Protocol\n * records).\n *\n * @see {@link buildAgent} for creating (simple) Agent instances.\n *\n * @example\n * ```typescript\n * const agent: Agent = {\n * did: 'did:plc:example123',\n * fetchHandler: async (path, init) => {\n * const url = new URL(path, 'https://bsky.social')\n * return fetch(url, init)\n * }\n * }\n * ```\n */\nexport interface Agent {\n /** The DID of the authenticated user, or `undefined` if unauthenticated. */\n readonly did?: DidString\n /** The fetch handler used to make HTTP requests. */\n fetchHandler: FetchHandler\n}\n\nexport function isAgent(value: unknown): value is Agent {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'fetchHandler' in value &&\n typeof value.fetchHandler === 'function' &&\n (!('did' in value) ||\n value.did === undefined ||\n typeof value.did === 'string')\n )\n}\n\nexport type AgentConfig = {\n /**\n * The identifier (DID) of the user represented by this agent.\n */\n did?: DidString\n\n /**\n * The service URL to make requests to. This can be a string, URL, or a\n * function that returns a string or URL. This is useful for dynamic URLs,\n * such as a service URL that changes based on authentication.\n */\n service: string | URL\n\n /**\n * Optional headers to include with every request made by this agent, unless\n * overridden by the request-specific headers provided to the fetch handler.\n */\n headers?: HeadersInit\n\n /**\n * Bring your own fetch implementation. Typically useful for testing, logging,\n * mocking, or adding retries, session management, signatures, proof of\n * possession (DPoP), SSRF protection, etc. Defaults to the global `fetch`\n * function.\n */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Options for creating an Agent.\n *\n * Can be a full {@link AgentConfig} object, or a simple service URL string/{@link URL}.\n */\nexport type AgentOptions = AgentConfig | string | URL\n\n/**\n * Creates an {@link Agent} from various input types.\n *\n * This factory function accepts an existing Agent (returned as-is), a service\n * URL, or a full configuration object. It handles the common case of creating\n * an unauthenticated agent from just a service URL.\n *\n * @param options - Agent instance, configuration object, or service URL\n * @returns A configured Agent ready for making requests\n * @throws {TypeError} If fetch() is not available in the environment\n *\n * @example // From URL string\n * ```typescript\n * const agent = buildAgent('https://public.api.bsky.app')\n * ```\n *\n * @example // From configuration\n * ```typescript\n * const agent = buildAgent({\n * did: 'did:plc:example',\n * service: 'https://bsky.social',\n * headers: { 'Authorization': 'Bearer ...' }\n * })\n * ```\n */\nexport function buildAgent<O extends Agent | AgentOptions>(\n options: O,\n): O extends Agent ? O : Agent\nexport function buildAgent(options: Agent | AgentOptions): Agent {\n if (isAgent(options)) return options\n\n const config: Agent | AgentConfig =\n typeof options === 'string' || options instanceof URL\n ? { did: undefined, service: options }\n : options\n\n const { service, fetch = globalThis.fetch } = config\n\n if (typeof fetch !== 'function') {\n throw new TypeError('fetch() is not available in this environment')\n }\n\n return {\n get did() {\n return config.did\n },\n\n async fetchHandler(path, init) {\n const headers =\n config.headers != null && init.headers != null\n ? mergeHeaders(config.headers, init.headers)\n : config.headers || init.headers\n\n return fetch(\n new URL(path, service),\n headers !== init.headers ? { ...init, headers } : init,\n )\n },\n }\n}\n\nfunction mergeHeaders(\n defaultHeaders: HeadersInit,\n requestHeaders: HeadersInit,\n): Headers {\n // We don't want to alter the original Headers objects, so we create a new one\n const result = new Headers(defaultHeaders)\n\n const overrides =\n requestHeaders instanceof Headers\n ? requestHeaders\n : new Headers(requestHeaders)\n\n for (const [key, value] of overrides.entries()) {\n result.set(key, value)\n }\n\n return result\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;AA0DA,0BAUC;AAiED,gCAiCC;AA5GD,SAAgB,OAAO,CAAC,KAAc;IACpC,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,K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,CAAC,EACtB,OAAO,KAAK,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CACvD,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC;AAED,SAAS,YAAY,CACnB,cAA2B,EAC3B,cAA2B;IAE3B,8EAA8E;IAC9E,MAAM,MAAM,GAAG,IAAI,OAAO,CAAC,cAAc,CAAC,CAAA;IAE1C,MAAM,SAAS,GACb,cAAc,YAAY,OAAO;QAC/B,CAAC,CAAC,cAAc;QAChB,CAAC,CAAC,IAAI,OAAO,CAAC,cAAc,CAAC,CAAA;IAEjC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC,OAAO,EAAE,EAAE,CAAC;QAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IACxB,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { DidString } from '@atproto/lex-schema'\n\n/**\n * A function that performs HTTP requests towards a service endpoint.\n *\n * The handler is responsible for adding the origin (protocol, hostname, and\n * port) to the provided path, typically based on authentication or service\n * configuration. The handler can also be responsible for adding any necessary\n * headers, such as authorization tokens.\n *\n * @param path - The URL path (pathname + query parameters) without the origin\n * @param init - Standard fetch RequestInit options\n * @returns A Promise resolving to the HTTP Response\n */\nexport type FetchHandler = (\n /**\n * The URL (pathname + query parameters) to make the request to, without the\n * origin. The origin (protocol, hostname, and port) must be added by this\n * {@link FetchHandler}, typically based on authentication or other factors.\n */\n path: `/${string}`,\n init: RequestInit,\n) => Promise<Response>\n\n/**\n * Core interface for making XRPC requests towards a specific service.\n *\n * An {@link Agent} encapsulates an identity and request handling for AT\n * Protocol operations. Agents will typically handle authentication, service URL\n * resolution, and other request configuration, allowing client code to make\n * requests without needing to manage these details directly. The key component\n * of an Agent is the {@link FetchHandler}, which is responsible for\n * constructing the full request URL and adding any necessary headers or\n * authentication tokens. The Agent's `did` property represents the\n * authenticated user's DID, if available, and can be used for operations that\n * require knowledge of the user's identity (such as creating AT Protocol\n * records).\n *\n * @see {@link buildAgent} for creating (simple) Agent instances.\n *\n * @example\n * ```typescript\n * const agent: Agent = {\n * did: 'did:plc:example123',\n * fetchHandler: async (path, init) => {\n * const url = new URL(path, 'https://bsky.social')\n * return fetch(url, init)\n * }\n * }\n * ```\n */\nexport interface Agent {\n /** The DID of the authenticated user, or `undefined` if unauthenticated. */\n readonly did?: DidString\n /** The fetch handler used to make HTTP requests. */\n fetchHandler: FetchHandler\n}\n\nexport function isAgent(value: unknown): value is Agent {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'fetchHandler' in value &&\n typeof value.fetchHandler === 'function' &&\n (!('did' in value) ||\n value.did === undefined ||\n typeof value.did === 'string')\n )\n}\n\nexport type AgentConfig = {\n /**\n * The identifier (DID) of the user represented by this agent.\n */\n did?: DidString\n\n /**\n * The service URL to make requests to. This can be a string, URL, or a\n * function that returns a string or URL. This is useful for dynamic URLs,\n * such as a service URL that changes based on authentication.\n */\n service: string | URL\n\n /**\n * Optional headers to include with every request made by this agent, unless\n * overridden by the request-specific headers provided to the fetch handler.\n */\n headers?: HeadersInit\n\n /**\n * Bring your own fetch implementation. Typically useful for testing, logging,\n * mocking, or adding retries, session management, signatures, proof of\n * possession (DPoP), SSRF protection, etc. Defaults to the global `fetch`\n * function.\n */\n fetch?: typeof globalThis.fetch\n}\n\n/**\n * Options for creating an Agent.\n *\n * Can be a full {@link AgentConfig} object, or a simple service URL string/{@link URL}.\n */\nexport type AgentOptions = AgentConfig | FetchHandler | string | URL\n\n/**\n * Creates an {@link Agent} from various input types.\n *\n * This factory function accepts an existing Agent (returned as-is), a service\n * URL, or a full configuration object. It handles the common case of creating\n * an unauthenticated agent from just a service URL.\n *\n * @param options - Agent instance, configuration object, or service URL\n * @returns A configured Agent ready for making requests\n * @throws {TypeError} If fetch() is not available in the environment\n *\n * @example // From URL string\n * ```typescript\n * const agent = buildAgent('https://public.api.bsky.app')\n * ```\n *\n * @example // From configuration\n * ```typescript\n * const agent = buildAgent({\n * did: 'did:plc:example',\n * service: 'https://bsky.social',\n * headers: { 'Authorization': 'Bearer ...' }\n * })\n * ```\n */\nexport function buildAgent<O extends Agent | AgentOptions>(\n options: O,\n): O extends Agent ? O : Agent\nexport function buildAgent(options: Agent | AgentOptions): Agent {\n const config: Agent | AgentConfig =\n typeof options === 'function'\n ? { did: undefined, fetchHandler: options }\n : typeof options === 'string' || options instanceof URL\n ? { did: undefined, service: options }\n : options\n\n if (isAgent(config)) return config\n\n const { service, fetch = globalThis.fetch } = config\n\n if (typeof fetch !== 'function') {\n throw new TypeError('fetch() is not available in this environment')\n }\n\n return {\n get did() {\n return config.did\n },\n\n async fetchHandler(path, init) {\n const headers =\n config.headers != null && init.headers != null\n ? mergeHeaders(config.headers, init.headers)\n : config.headers || init.headers\n\n return fetch(\n new URL(path, service),\n headers !== init.headers ? { ...init, headers } : init,\n )\n },\n }\n}\n\nfunction mergeHeaders(\n defaultHeaders: HeadersInit,\n requestHeaders: HeadersInit,\n): Headers {\n // We don't want to alter the original Headers objects, so we create a new one\n const result = new Headers(defaultHeaders)\n\n const overrides =\n requestHeaders instanceof Headers\n ? requestHeaders\n : new Headers(requestHeaders)\n\n for (const [key, value] of overrides.entries()) {\n result.set(key, value)\n }\n\n return result\n}\n"]}
package/dist/errors.d.ts CHANGED
@@ -199,17 +199,11 @@ export declare class XrpcInvalidResponseError<M extends Procedure | Query = Proc
199
199
  toDownstreamError(): DownstreamError;
200
200
  }
201
201
  /**
202
- * Error class for internal/client-side errors during XRPC requests.
202
+ * Error class for unexpected internal/client-side errors during XRPC requests.
203
203
  *
204
- * This represents errors that occur before or during the request that are not
205
- * server responses, such as:
206
- * - Network errors (connection refused, DNS failure)
207
- * - Request timeouts
208
- * - Request aborted via AbortSignal
209
- * - Invalid request construction
210
- *
211
- * The error code is always 'InternalServerError' and these errors are
212
- * optimistically considered retryable.
204
+ * The error code is always 'InternalServerError' and these errors not
205
+ * considered retryable as they stem from unforeseen issues in the
206
+ * implementation.
213
207
  *
214
208
  * @typeParam M - The XRPC method type
215
209
  */
@@ -217,8 +211,25 @@ export declare class XrpcInternalError<M extends Procedure | Query = Procedure |
217
211
  name: string;
218
212
  constructor(method: M, message?: string, options?: ErrorOptions);
219
213
  get reason(): this;
220
- shouldRetry(): true;
221
- toJSON(): LexErrorData<'InternalServerError'>;
214
+ shouldRetry(): boolean;
215
+ toJSON(): LexErrorData;
216
+ toDownstreamError(): DownstreamError;
217
+ }
218
+ /**
219
+ * Special case of XrpcInternalError that specifically represents errors thrown
220
+ * by {@link Agent.fetchHandler} during the XRPC request. This includes:
221
+ * - Network errors (connection refused, DNS failure)
222
+ * - Request timeouts
223
+ * - Request aborted via AbortSignal
224
+ *
225
+ * These errors are optimistically considered retryable, as many fetch errors
226
+ * are transient and may succeed on retry.
227
+ */
228
+ export declare class XrpcFetchError<M extends Procedure | Query = Procedure | Query> extends XrpcInternalError<M> {
229
+ name: string;
230
+ constructor(method: M, cause: unknown);
231
+ shouldRetry(): boolean;
232
+ toJSON(): LexErrorData;
222
233
  toDownstreamError(): DownstreamError;
223
234
  }
224
235
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AACxE,OAAO,EACL,gBAAgB,EAChB,kBAAkB,EAClB,SAAS,EACT,KAAK,EACL,aAAa,EAEd,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAA;AAC/C,OAAO,EACL,eAAe,EAEhB,MAAM,uBAAuB,CAAA;AAE9B,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,IAAI;IACnE,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,CAAC,EAAE,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AAC;IAC5B,IAAI,SAAmB;gBAEX,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,OAAO;IAK5B,WAAW,IAAI,OAAO;IAQtB,MAAM,IAAI,YAAY;IAKtB,iBAAiB,IAAI,eAAe;CAQ9C;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,WAAW,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,GAAG,SAAS,GAAG,KAAK,IAEnE,iBAAiB,CAAC,CAAC,CAAC,GAEpB,iBAAiB,CAAC,CAAC,CAAC,GAEpB,iBAAiB,CAAC,CAAC,CAAC,CAAA;AAExB;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,EACvD,MAAM,EAAE,CAAC,EACT,KAAK,EAAE,OAAO,GACb,WAAW,CAAC,CAAC,CAAC,CAUhB"}
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.XrpcInternalError = exports.XrpcInvalidResponseError = exports.XrpcUpstreamError = exports.XrpcAuthenticationError = exports.XrpcResponseError = exports.XrpcError = exports.LexError = exports.RETRYABLE_HTTP_STATUS_CODES = void 0;
3
+ exports.XrpcFetchError = exports.XrpcInternalError = exports.XrpcInvalidResponseError = exports.XrpcUpstreamError = exports.XrpcAuthenticationError = exports.XrpcResponseError = exports.XrpcError = exports.LexError = exports.RETRYABLE_HTTP_STATUS_CODES = void 0;
4
4
  exports.isXrpcErrorPayload = isXrpcErrorPayload;
5
5
  exports.asXrpcFailure = asXrpcFailure;
6
6
  const lex_data_1 = require("@atproto/lex-data");
@@ -251,17 +251,11 @@ class XrpcInvalidResponseError extends XrpcUpstreamError {
251
251
  }
252
252
  exports.XrpcInvalidResponseError = XrpcInvalidResponseError;
253
253
  /**
254
- * Error class for internal/client-side errors during XRPC requests.
254
+ * Error class for unexpected internal/client-side errors during XRPC requests.
255
255
  *
256
- * This represents errors that occur before or during the request that are not
257
- * server responses, such as:
258
- * - Network errors (connection refused, DNS failure)
259
- * - Request timeouts
260
- * - Request aborted via AbortSignal
261
- * - Invalid request construction
262
- *
263
- * The error code is always 'InternalServerError' and these errors are
264
- * optimistically considered retryable.
256
+ * The error code is always 'InternalServerError' and these errors not
257
+ * considered retryable as they stem from unforeseen issues in the
258
+ * implementation.
265
259
  *
266
260
  * @typeParam M - The XRPC method type
267
261
  */
@@ -274,11 +268,7 @@ class XrpcInternalError extends XrpcError {
274
268
  return this;
275
269
  }
276
270
  shouldRetry() {
277
- // Ideally, we would inspect the reason to determine if it's retryable
278
- // (by detecting network errors, timeouts, etc.). Since these cases are
279
- // highly platform-dependent, we optimistically assume all internal
280
- // errors are retryable.
281
- return true;
271
+ return false;
282
272
  }
283
273
  toJSON() {
284
274
  // @NOTE Do not expose internal error details to downstream clients
@@ -289,6 +279,43 @@ class XrpcInternalError extends XrpcError {
289
279
  }
290
280
  }
291
281
  exports.XrpcInternalError = XrpcInternalError;
282
+ /**
283
+ * Special case of XrpcInternalError that specifically represents errors thrown
284
+ * by {@link Agent.fetchHandler} during the XRPC request. This includes:
285
+ * - Network errors (connection refused, DNS failure)
286
+ * - Request timeouts
287
+ * - Request aborted via AbortSignal
288
+ *
289
+ * These errors are optimistically considered retryable, as many fetch errors
290
+ * are transient and may succeed on retry.
291
+ */
292
+ class XrpcFetchError extends XrpcInternalError {
293
+ name = 'XrpcFetchError';
294
+ constructor(method, cause) {
295
+ const message = cause instanceof Error ? cause.message : String(cause);
296
+ super(method, `Unexpected fetchHandler() error: ${message}`, { cause });
297
+ }
298
+ shouldRetry() {
299
+ // Ideally, we would inspect the reason to determine if it's retryable (by
300
+ // detecting network errors, timeouts, etc.). Since these cases are highly
301
+ // platform-dependent, we optimistically assume all fetch errors are
302
+ // transient and retryable.
303
+ return true;
304
+ }
305
+ toJSON() {
306
+ // @NOTE Do not expose internal error details to downstream clients
307
+ return { error: this.error, message: 'Failed to perform upstream request' };
308
+ }
309
+ toDownstreamError() {
310
+ // While it might technically be a 500 error, we use 502 Bad Gateway here to
311
+ // indicate that the error occurred while communicating with the upstream
312
+ // server, allowing downstream clients to distinguish between errors in our
313
+ // internal processing (500) and errors in the upstream server or network
314
+ // (502).
315
+ return { status: 502, body: this.toJSON() };
316
+ }
317
+ }
318
+ exports.XrpcFetchError = XrpcFetchError;
292
319
  /**
293
320
  * Converts an unknown error into an appropriate {@link XrpcFailure} type.
294
321
  *
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAmEA,gDAQC;AAmXD,sCAaC;AA3cD,gDAAwE;AAwC/D,yFAxCA,mBAAQ,OAwCA;AAvCjB,oDAO4B;AAE5B,+DAG8B;AAS9B;;;;;;;;;;;;;GAaG;AACU,QAAA,2BAA2B,GAAwB,IAAI,GAAG,CAAC;IACtE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;CAC5C,CAAC,CAAA;AAiBF;;;;;;;;;;;GAWG;AACH,SAAgB,kBAAkB,CAChC,OAA+C;IAE/C,OAAO,CACL,OAAO,IAAI,IAAI;QACf,OAAO,CAAC,QAAQ,KAAK,kBAAkB;QACvC,+BAAkB,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CACzC,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAsB,SAKpB,SAAQ,mBAAW;IAMR;IAHX,IAAI,GAAG,WAAW,CAAA;IAElB,YACW,MAAS,EAClB,KAAQ,EACR,UAAkB,GAAG,KAAK,oBAAoB,EAC9C,OAAsB;QAEtB,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAA;QALrB,WAAM,GAAN,MAAM,CAAG;IAMpB,CAAC;IAED;;OAEG;IACM,OAAO,GAAG,KAAc,CAAA;IAcjC,mB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O,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { LexError, LexErrorCode, LexErrorData } from '@atproto/lex-data'\nimport {\n InferMethodError,\n LexValidationError,\n Procedure,\n Query,\n ResultFailure,\n lexErrorDataSchema,\n} from '@atproto/lex-schema'\nimport { XrpcResponsePayload } from './util.js'\nimport {\n WWWAuthenticate,\n parseWWWAuthenticateHeader,\n} from './www-authenticate.js'\n\nexport type DownstreamError<N extends LexErrorCode = LexErrorCode> = {\n status: number\n headers?: Headers\n encoding?: 'application/json'\n body: LexErrorData<N>\n}\n\n/**\n * HTTP status codes that indicate a transient error that may succeed on retry.\n *\n * Includes:\n * - 408 Request Timeout\n * - 425 Too Early\n * - 429 Too Many Requests (rate limited)\n * - 500 Internal Server Error\n * - 502 Bad Gateway\n * - 503 Service Unavailable\n * - 504 Gateway Timeout\n * - 522 Connection Timed Out (Cloudflare)\n * - 524 A Timeout Occurred (Cloudflare)\n */\nexport const RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, 425, 429, 500, 502, 503, 504, 522, 524,\n])\n\nexport { LexError }\nexport type { LexErrorCode, LexErrorData }\n\n/**\n * The payload structure for XRPC error responses.\n *\n * All XRPC errors return JSON with an `error` code and optional `message`.\n *\n * @typeParam N - The specific error code type\n */\nexport type XrpcErrorPayload<N extends LexErrorCode = LexErrorCode> = {\n body: LexErrorData<N>\n encoding: 'application/json'\n}\n\n/**\n * All unsuccessful responses should follow a standard error response\n * schema. The Content-Type should be application/json, and the payload\n * should be a JSON object with the following fields:\n *\n * - `error` (string, required): type name of the error (generic ASCII\n * constant, no whitespace)\n * - `message` (string, optional): description of the error, appropriate for\n * display to humans\n *\n * This function checks whether a given payload matches this schema.\n */\nexport function isXrpcErrorPayload(\n payload: XrpcResponsePayload | null | undefined,\n): payload is XrpcErrorPayload {\n return (\n payload != null &&\n payload.encoding === 'application/json' &&\n lexErrorDataSchema.matches(payload.body)\n )\n}\n\n/**\n * Abstract base class for all XRPC errors.\n *\n * Extends {@link LexError} and implements {@link ResultFailure} for use with\n * safe/result-based error handling patterns.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n * @typeParam N - The error code type\n * @typeParam TReason - The reason type for ResultFailure\n *\n * @see {@link XrpcResponseError} - For valid XRPC error responses\n * @see {@link XrpcUpstreamError} - For invalid/unexpected responses\n * @see {@link XrpcInternalError} - For network/internal errors\n */\nexport abstract class XrpcError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = LexErrorCode,\n TReason = unknown,\n >\n extends LexError<N>\n implements ResultFailure<TReason>\n{\n name = 'XrpcError'\n\n constructor(\n readonly method: M,\n error: N,\n message: string = `${error} Lexicon RPC error`,\n options?: ErrorOptions,\n ) {\n super(error, message, options)\n }\n\n /**\n * @see {@link ResultFailure.success}\n */\n readonly success = false as const\n\n /**\n * @see {@link ResultFailure.reason}\n */\n abstract readonly reason: TReason\n\n /**\n * Indicates whether the error is transient and can be retried.\n */\n abstract shouldRetry(): boolean\n\n abstract toDownstreamError(): DownstreamError\n\n matchesSchemaErrors(): this is XrpcError<M, InferMethodError<M>> {\n return this.method.errors?.includes(this.error) ?? false\n }\n}\n\n/**\n * Error class for valid XRPC error responses from the server.\n *\n * This represents a properly formatted XRPC error where the server returned\n * a non-2xx status with a valid JSON error payload containing `error` and\n * optional `message` fields.\n *\n * Use {@link matchesSchemaErrors} to check if the error matches the method's declared\n * error types for type-safe error handling.\n *\n * @typeParam M - The XRPC method type\n * @typeParam N - The error code type (inferred from method or generic)\n *\n * @example Handling specific errors\n * ```typescript\n * try {\n * await client.xrpc(someMethod, options)\n * } catch (err) {\n * if (err instanceof XrpcResponseError && err.error === 'RecordNotFound') {\n * // Handle not found case\n * }\n * }\n * ```\n */\nexport class XrpcResponseError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = InferMethodError<M> | LexErrorCode,\n> extends XrpcError<M, N, XrpcResponseError<M, N>> {\n name = 'XrpcResponseError'\n\n constructor(\n method: M,\n readonly response: Response,\n readonly payload: XrpcErrorPayload<N>,\n options?: ErrorOptions,\n ) {\n const { error, message } = payload.body\n super(method, error, message, options)\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): boolean {\n return RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)\n }\n\n override toJSON(): LexErrorData<N> {\n return this.payload.body\n }\n\n override toDownstreamError(): DownstreamError {\n // If the upstream server returned a 5xx error, we want to return a 502 Bad\n // Gateway to downstream clients, as the issue is with the upstream server,\n // not us. We still return the original error code and message in the body\n // for transparency, but we do not want to expose internal server errors\n // from the upstream server as-is to downstream clients.\n return {\n status: this.response.status === 500 ? 502 : this.status,\n headers: stripHopByHopHeaders(this.headers),\n body: this.toJSON(),\n }\n }\n\n get status(): number {\n return this.response.status\n }\n\n get headers(): Headers {\n return this.response.headers\n }\n\n get body(): LexErrorData<N> {\n return this.payload.body\n }\n}\n\nexport type { WWWAuthenticate }\n\n/**\n * Error class for 401 Unauthorized XRPC responses.\n *\n * Extends {@link XrpcResponseError} with access to parsed WWW-Authenticate header\n * information, useful for implementing authentication flows.\n *\n * Authentication errors are never retryable as they require user intervention\n * (e.g., re-authentication, token refresh).\n *\n * @typeParam M - The XRPC method type\n * @typeParam N - The error code type\n *\n * @example Handling authentication errors\n * ```typescript\n * try {\n * await client.xrpc(someMethod, options)\n * } catch (err) {\n * if (err instanceof XrpcAuthenticationError) {\n * const { DPoP } = err.wwwAuthenticate\n * if (DPoP?.error === 'use_dpop_nonce') {\n * // Handle DPoP nonce requirement\n * }\n * }\n * }\n * ```\n */\nexport class XrpcAuthenticationError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = LexErrorCode,\n> extends XrpcResponseError<M, N> {\n name = 'XrpcAuthenticationError'\n\n override shouldRetry(): boolean {\n return false\n }\n\n #wwwAuthenticateCached?: WWWAuthenticate\n /**\n * Parsed WWW-Authenticate header from the response.\n * Contains authentication scheme parameters (e.g., Bearer realm, DPoP nonce).\n */\n get wwwAuthenticate(): WWWAuthenticate {\n return (this.#wwwAuthenticateCached ??=\n parseWWWAuthenticateHeader(\n this.response.headers.get('www-authenticate'),\n ) ?? {})\n }\n\n override toDownstreamError(): DownstreamError {\n return {\n status: 401,\n headers: stripHopByHopHeaders(this.headers),\n body: this.toJSON(),\n }\n }\n}\n\n/**\n * Error class for invalid or unprocessable XRPC responses from upstream servers.\n *\n * This occurs when the server returns a response that doesn't conform to the\n * XRPC protocol, such as:\n * - Missing or invalid Content-Type header\n * - Response body that doesn't match the method's output schema\n * - Non-JSON error responses\n * - Responses from non-XRPC endpoints\n *\n * The error code is always 'UpstreamFailure' and maps to HTTP 502 Bad Gateway\n * when converted to a response.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcUpstreamError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcError<M, 'UpstreamFailure', XrpcUpstreamError<M>> {\n name = 'XrpcUpstreamError'\n\n constructor(\n method: M,\n readonly response: Response,\n readonly payload: XrpcResponsePayload | null = null,\n message: string = `Unexpected upstream XRPC response`,\n options?: ErrorOptions,\n ) {\n super(method, 'UpstreamFailure', message, options)\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): boolean {\n return RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)\n }\n\n override toDownstreamError(): DownstreamError {\n return { status: 502, body: this.toJSON() }\n }\n}\n\n/**\n * Error class for invalid XRPC responses that fail schema validation.\n *\n * This is a specific type of {@link XrpcUpstreamError} that indicates the\n * upstream server returned a response that was structurally valid but did not\n * conform to the expected schema for the method. This likely indicates a\n * mismatch between client and server versions or an issue with the server's\n * XRPC implementation.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcInvalidResponseError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcUpstreamError<M> {\n name = 'XrpcInvalidResponseError'\n\n constructor(\n method: M,\n response: Response,\n payload: XrpcResponsePayload,\n readonly cause: LexValidationError,\n ) {\n super(method, response, payload, `Invalid response: ${cause.message}`, {\n cause,\n })\n }\n\n override toDownstreamError(): DownstreamError {\n // @NOTE This could be reflected as both a 500 (\"we\" are at fault) and 502\n // (\"they\" are at fault). We are using 502 here to allow downstream clients\n // to determine that the issue lies at the interface between us and the\n // upstream server, rather than an issue with our internal processing.\n return { status: 502, body: this.toJSON() }\n }\n}\n\n/**\n * Error class for internal/client-side errors during XRPC requests.\n *\n * This represents errors that occur before or during the request that are not\n * server responses, such as:\n * - Network errors (connection refused, DNS failure)\n * - Request timeouts\n * - Request aborted via AbortSignal\n * - Invalid request construction\n *\n * The error code is always 'InternalServerError' and these errors are\n * optimistically considered retryable.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcInternalError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcError<M, 'InternalServerError', XrpcInternalError<M>> {\n name = 'XrpcInternalError'\n\n constructor(method: M, message?: string, options?: ErrorOptions) {\n super(\n method,\n 'InternalServerError',\n message ?? 'Unable to fulfill XRPC request',\n options,\n )\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): true {\n // Ideally, we would inspect the reason to determine if it's retryable\n // (by detecting network errors, timeouts, etc.). Since these cases are\n // highly platform-dependent, we optimistically assume all internal\n // errors are retryable.\n return true\n }\n\n override toJSON(): LexErrorData<'InternalServerError'> {\n // @NOTE Do not expose internal error details to downstream clients\n return { error: this.error, message: 'Internal Server Error' }\n }\n\n override toDownstreamError(): DownstreamError {\n return { status: 500, body: this.toJSON() }\n }\n}\n\n/**\n * Union type of all possible XRPC failure types.\n *\n * Used as the return type for safe/non-throwing XRPC methods. Check the\n * `success` property to distinguish between success and failure:\n *\n * @typeParam M - The XRPC method type\n *\n * @example\n * ```typescript\n * const result = await client.xrpcSafe(someMethod, options)\n * if (result.success) {\n * console.log(result.body) // XrpcResponse\n * } else {\n * // result is XrpcFailure (XrpcResponseError | XrpcUpstreamError | XrpcInternalError)\n * console.error(result.error, result.message)\n * }\n * ```\n */\nexport type XrpcFailure<M extends Procedure | Query = Procedure | Query> =\n // The server returned a valid XRPC error response\n | XrpcResponseError<M>\n // The response was not a valid XRPC response, or it does not match the schema\n | XrpcUpstreamError<M>\n // Something went wrong (network error, etc.)\n | XrpcInternalError<M>\n\n/**\n * Converts an unknown error into an appropriate {@link XrpcFailure} type.\n *\n * If the error is already an XrpcFailure for the given method, returns it as-is.\n * Otherwise, wraps it in an {@link XrpcInternalError}.\n *\n * @param method - The XRPC method that was called\n * @param cause - The error to convert\n * @returns An XrpcFailure instance\n *\n * @example\n * ```typescript\n * try {\n * const response = await fetch(...)\n * // ... process response\n * } catch (err) {\n * return asXrpcFailure(method, err)\n * }\n * ```\n */\nexport function asXrpcFailure<M extends Procedure | Query>(\n method: M,\n cause: unknown,\n): XrpcFailure<M> {\n if (\n cause instanceof XrpcResponseError ||\n cause instanceof XrpcUpstreamError ||\n cause instanceof XrpcInternalError\n ) {\n if (cause.method === method) return cause\n }\n\n return new XrpcInternalError(method, undefined, { cause })\n}\n\nconst HOP_BY_HOP_HEADERS = new Set([\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n])\n\nfunction stripHopByHopHeaders(headers: Headers): Headers {\n const result = new Headers(headers)\n\n // Remove statically known hop-by-hop headers\n for (const name of HOP_BY_HOP_HEADERS) {\n result.delete(name)\n }\n\n // Remove headers listed in the \"Connection\" header\n const connection = headers.get('connection')\n if (connection) {\n for (const name of connection.split(',')) {\n result.delete(name.trim())\n }\n }\n\n // These are not actually hop-by-hop headers, but we remove them because the\n // upstream payload gets parsed and re-serialized, so content length and\n // encoding may no longer be accurate.\n result.delete('content-length')\n result.delete('content-encoding')\n\n return result\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAqEA,gDAQC;AAoZD,sCAaC;AA9eD,gDAAwE;AA0C/D,yFA1CA,mBAAQ,OA0CA;AAzCjB,oDAO4B;AAI5B,+DAG8B;AAS9B;;;;;;;;;;;;;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AAC,IAAI,EAAE,CAAC,CAAA;QAC5B,CAAC;IACH,CAAC;IAED,4EAA4E;IAC5E,wEAAwE;IACxE,sCAAsC;IACtC,MAAM,CAAC,MAAM,CAAC,gBAAgB,CAAC,CAAA;IAC/B,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAA;IAEjC,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { LexError, LexErrorCode, LexErrorData } from '@atproto/lex-data'\nimport {\n InferMethodError,\n LexValidationError,\n Procedure,\n Query,\n ResultFailure,\n lexErrorDataSchema,\n} from '@atproto/lex-schema'\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { Agent } from './agent.js'\nimport { XrpcResponsePayload } from './util.js'\nimport {\n WWWAuthenticate,\n parseWWWAuthenticateHeader,\n} from './www-authenticate.js'\n\nexport type DownstreamError<N extends LexErrorCode = LexErrorCode> = {\n status: number\n headers?: Headers\n encoding?: 'application/json'\n body: LexErrorData<N>\n}\n\n/**\n * HTTP status codes that indicate a transient error that may succeed on retry.\n *\n * Includes:\n * - 408 Request Timeout\n * - 425 Too Early\n * - 429 Too Many Requests (rate limited)\n * - 500 Internal Server Error\n * - 502 Bad Gateway\n * - 503 Service Unavailable\n * - 504 Gateway Timeout\n * - 522 Connection Timed Out (Cloudflare)\n * - 524 A Timeout Occurred (Cloudflare)\n */\nexport const RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, 425, 429, 500, 502, 503, 504, 522, 524,\n])\n\nexport { LexError }\nexport type { LexErrorCode, LexErrorData }\n\n/**\n * The payload structure for XRPC error responses.\n *\n * All XRPC errors return JSON with an `error` code and optional `message`.\n *\n * @typeParam N - The specific error code type\n */\nexport type XrpcErrorPayload<N extends LexErrorCode = LexErrorCode> = {\n body: LexErrorData<N>\n encoding: 'application/json'\n}\n\n/**\n * All unsuccessful responses should follow a standard error response\n * schema. The Content-Type should be application/json, and the payload\n * should be a JSON object with the following fields:\n *\n * - `error` (string, required): type name of the error (generic ASCII\n * constant, no whitespace)\n * - `message` (string, optional): description of the error, appropriate for\n * display to humans\n *\n * This function checks whether a given payload matches this schema.\n */\nexport function isXrpcErrorPayload(\n payload: XrpcResponsePayload | null | undefined,\n): payload is XrpcErrorPayload {\n return (\n payload != null &&\n payload.encoding === 'application/json' &&\n lexErrorDataSchema.matches(payload.body)\n )\n}\n\n/**\n * Abstract base class for all XRPC errors.\n *\n * Extends {@link LexError} and implements {@link ResultFailure} for use with\n * safe/result-based error handling patterns.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n * @typeParam N - The error code type\n * @typeParam TReason - The reason type for ResultFailure\n *\n * @see {@link XrpcResponseError} - For valid XRPC error responses\n * @see {@link XrpcUpstreamError} - For invalid/unexpected responses\n * @see {@link XrpcInternalError} - For network/internal errors\n */\nexport abstract class XrpcError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = LexErrorCode,\n TReason = unknown,\n >\n extends LexError<N>\n implements ResultFailure<TReason>\n{\n name = 'XrpcError'\n\n constructor(\n readonly method: M,\n error: N,\n message: string = `${error} Lexicon RPC error`,\n options?: ErrorOptions,\n ) {\n super(error, message, options)\n }\n\n /**\n * @see {@link ResultFailure.success}\n */\n readonly success = false as const\n\n /**\n * @see {@link ResultFailure.reason}\n */\n abstract readonly reason: TReason\n\n /**\n * Indicates whether the error is transient and can be retried.\n */\n abstract shouldRetry(): boolean\n\n abstract toDownstreamError(): DownstreamError\n\n matchesSchemaErrors(): this is XrpcError<M, InferMethodError<M>> {\n return this.method.errors?.includes(this.error) ?? false\n }\n}\n\n/**\n * Error class for valid XRPC error responses from the server.\n *\n * This represents a properly formatted XRPC error where the server returned\n * a non-2xx status with a valid JSON error payload containing `error` and\n * optional `message` fields.\n *\n * Use {@link matchesSchemaErrors} to check if the error matches the method's declared\n * error types for type-safe error handling.\n *\n * @typeParam M - The XRPC method type\n * @typeParam N - The error code type (inferred from method or generic)\n *\n * @example Handling specific errors\n * ```typescript\n * try {\n * await client.xrpc(someMethod, options)\n * } catch (err) {\n * if (err instanceof XrpcResponseError && err.error === 'RecordNotFound') {\n * // Handle not found case\n * }\n * }\n * ```\n */\nexport class XrpcResponseError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = InferMethodError<M> | LexErrorCode,\n> extends XrpcError<M, N, XrpcResponseError<M, N>> {\n name = 'XrpcResponseError'\n\n constructor(\n method: M,\n readonly response: Response,\n readonly payload: XrpcErrorPayload<N>,\n options?: ErrorOptions,\n ) {\n const { error, message } = payload.body\n super(method, error, message, options)\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): boolean {\n return RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)\n }\n\n override toJSON(): LexErrorData<N> {\n return this.payload.body\n }\n\n override toDownstreamError(): DownstreamError {\n // If the upstream server returned a 5xx error, we want to return a 502 Bad\n // Gateway to downstream clients, as the issue is with the upstream server,\n // not us. We still return the original error code and message in the body\n // for transparency, but we do not want to expose internal server errors\n // from the upstream server as-is to downstream clients.\n return {\n status: this.response.status === 500 ? 502 : this.status,\n headers: stripHopByHopHeaders(this.headers),\n body: this.toJSON(),\n }\n }\n\n get status(): number {\n return this.response.status\n }\n\n get headers(): Headers {\n return this.response.headers\n }\n\n get body(): LexErrorData<N> {\n return this.payload.body\n }\n}\n\nexport type { WWWAuthenticate }\n\n/**\n * Error class for 401 Unauthorized XRPC responses.\n *\n * Extends {@link XrpcResponseError} with access to parsed WWW-Authenticate header\n * information, useful for implementing authentication flows.\n *\n * Authentication errors are never retryable as they require user intervention\n * (e.g., re-authentication, token refresh).\n *\n * @typeParam M - The XRPC method type\n * @typeParam N - The error code type\n *\n * @example Handling authentication errors\n * ```typescript\n * try {\n * await client.xrpc(someMethod, options)\n * } catch (err) {\n * if (err instanceof XrpcAuthenticationError) {\n * const { DPoP } = err.wwwAuthenticate\n * if (DPoP?.error === 'use_dpop_nonce') {\n * // Handle DPoP nonce requirement\n * }\n * }\n * }\n * ```\n */\nexport class XrpcAuthenticationError<\n M extends Procedure | Query = Procedure | Query,\n N extends LexErrorCode = LexErrorCode,\n> extends XrpcResponseError<M, N> {\n name = 'XrpcAuthenticationError'\n\n override shouldRetry(): boolean {\n return false\n }\n\n #wwwAuthenticateCached?: WWWAuthenticate\n /**\n * Parsed WWW-Authenticate header from the response.\n * Contains authentication scheme parameters (e.g., Bearer realm, DPoP nonce).\n */\n get wwwAuthenticate(): WWWAuthenticate {\n return (this.#wwwAuthenticateCached ??=\n parseWWWAuthenticateHeader(\n this.response.headers.get('www-authenticate'),\n ) ?? {})\n }\n\n override toDownstreamError(): DownstreamError {\n return {\n status: 401,\n headers: stripHopByHopHeaders(this.headers),\n body: this.toJSON(),\n }\n }\n}\n\n/**\n * Error class for invalid or unprocessable XRPC responses from upstream servers.\n *\n * This occurs when the server returns a response that doesn't conform to the\n * XRPC protocol, such as:\n * - Missing or invalid Content-Type header\n * - Response body that doesn't match the method's output schema\n * - Non-JSON error responses\n * - Responses from non-XRPC endpoints\n *\n * The error code is always 'UpstreamFailure' and maps to HTTP 502 Bad Gateway\n * when converted to a response.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcUpstreamError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcError<M, 'UpstreamFailure', XrpcUpstreamError<M>> {\n name = 'XrpcUpstreamError'\n\n constructor(\n method: M,\n readonly response: Response,\n readonly payload: XrpcResponsePayload | null = null,\n message: string = `Unexpected upstream XRPC response`,\n options?: ErrorOptions,\n ) {\n super(method, 'UpstreamFailure', message, options)\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): boolean {\n return RETRYABLE_HTTP_STATUS_CODES.has(this.response.status)\n }\n\n override toDownstreamError(): DownstreamError {\n return { status: 502, body: this.toJSON() }\n }\n}\n\n/**\n * Error class for invalid XRPC responses that fail schema validation.\n *\n * This is a specific type of {@link XrpcUpstreamError} that indicates the\n * upstream server returned a response that was structurally valid but did not\n * conform to the expected schema for the method. This likely indicates a\n * mismatch between client and server versions or an issue with the server's\n * XRPC implementation.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcInvalidResponseError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcUpstreamError<M> {\n name = 'XrpcInvalidResponseError'\n\n constructor(\n method: M,\n response: Response,\n payload: XrpcResponsePayload,\n readonly cause: LexValidationError,\n ) {\n super(method, response, payload, `Invalid response: ${cause.message}`, {\n cause,\n })\n }\n\n override toDownstreamError(): DownstreamError {\n // @NOTE This could be reflected as both a 500 (\"we\" are at fault) and 502\n // (\"they\" are at fault). We are using 502 here to allow downstream clients\n // to determine that the issue lies at the interface between us and the\n // upstream server, rather than an issue with our internal processing.\n return { status: 502, body: this.toJSON() }\n }\n}\n\n/**\n * Error class for unexpected internal/client-side errors during XRPC requests.\n *\n * The error code is always 'InternalServerError' and these errors not\n * considered retryable as they stem from unforeseen issues in the\n * implementation.\n *\n * @typeParam M - The XRPC method type\n */\nexport class XrpcInternalError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcError<M, 'InternalServerError', XrpcInternalError<M>> {\n name = 'XrpcInternalError'\n\n constructor(method: M, message?: string, options?: ErrorOptions) {\n super(\n method,\n 'InternalServerError',\n message ?? 'Unable to fulfill XRPC request',\n options,\n )\n }\n\n override get reason(): this {\n return this\n }\n\n override shouldRetry(): boolean {\n return false\n }\n\n override toJSON(): LexErrorData {\n // @NOTE Do not expose internal error details to downstream clients\n return { error: this.error, message: 'Internal Server Error' }\n }\n\n override toDownstreamError(): DownstreamError {\n return { status: 500, body: this.toJSON() }\n }\n}\n\n/**\n * Special case of XrpcInternalError that specifically represents errors thrown\n * by {@link Agent.fetchHandler} during the XRPC request. This includes:\n * - Network errors (connection refused, DNS failure)\n * - Request timeouts\n * - Request aborted via AbortSignal\n *\n * These errors are optimistically considered retryable, as many fetch errors\n * are transient and may succeed on retry.\n */\nexport class XrpcFetchError<\n M extends Procedure | Query = Procedure | Query,\n> extends XrpcInternalError<M> {\n name = 'XrpcFetchError'\n\n constructor(method: M, cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause)\n super(method, `Unexpected fetchHandler() error: ${message}`, { cause })\n }\n\n override shouldRetry(): boolean {\n // Ideally, we would inspect the reason to determine if it's retryable (by\n // detecting network errors, timeouts, etc.). Since these cases are highly\n // platform-dependent, we optimistically assume all fetch errors are\n // transient and retryable.\n return true\n }\n\n override toJSON(): LexErrorData {\n // @NOTE Do not expose internal error details to downstream clients\n return { error: this.error, message: 'Failed to perform upstream request' }\n }\n\n override toDownstreamError(): DownstreamError {\n // While it might technically be a 500 error, we use 502 Bad Gateway here to\n // indicate that the error occurred while communicating with the upstream\n // server, allowing downstream clients to distinguish between errors in our\n // internal processing (500) and errors in the upstream server or network\n // (502).\n return { status: 502, body: this.toJSON() }\n }\n}\n\n/**\n * Union type of all possible XRPC failure types.\n *\n * Used as the return type for safe/non-throwing XRPC methods. Check the\n * `success` property to distinguish between success and failure:\n *\n * @typeParam M - The XRPC method type\n *\n * @example\n * ```typescript\n * const result = await client.xrpcSafe(someMethod, options)\n * if (result.success) {\n * console.log(result.body) // XrpcResponse\n * } else {\n * // result is XrpcFailure (XrpcResponseError | XrpcUpstreamError | XrpcInternalError)\n * console.error(result.error, result.message)\n * }\n * ```\n */\nexport type XrpcFailure<M extends Procedure | Query = Procedure | Query> =\n // The server returned a valid XRPC error response\n | XrpcResponseError<M>\n // The response was not a valid XRPC response, or it does not match the schema\n | XrpcUpstreamError<M>\n // Something went wrong (network error, etc.)\n | XrpcInternalError<M>\n\n/**\n * Converts an unknown error into an appropriate {@link XrpcFailure} type.\n *\n * If the error is already an XrpcFailure for the given method, returns it as-is.\n * Otherwise, wraps it in an {@link XrpcInternalError}.\n *\n * @param method - The XRPC method that was called\n * @param cause - The error to convert\n * @returns An XrpcFailure instance\n *\n * @example\n * ```typescript\n * try {\n * const response = await fetch(...)\n * // ... process response\n * } catch (err) {\n * return asXrpcFailure(method, err)\n * }\n * ```\n */\nexport function asXrpcFailure<M extends Procedure | Query>(\n method: M,\n cause: unknown,\n): XrpcFailure<M> {\n if (\n cause instanceof XrpcResponseError ||\n cause instanceof XrpcUpstreamError ||\n cause instanceof XrpcInternalError\n ) {\n if (cause.method === method) return cause\n }\n\n return new XrpcInternalError(method, undefined, { cause })\n}\n\nconst HOP_BY_HOP_HEADERS = new Set([\n 'connection',\n 'keep-alive',\n 'proxy-authenticate',\n 'proxy-authorization',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n])\n\nfunction stripHopByHopHeaders(headers: Headers): Headers {\n const result = new Headers(headers)\n\n // Remove statically known hop-by-hop headers\n for (const name of HOP_BY_HOP_HEADERS) {\n result.delete(name)\n }\n\n // Remove headers listed in the \"Connection\" header\n const connection = headers.get('connection')\n if (connection) {\n for (const name of connection.split(',')) {\n result.delete(name.trim())\n }\n }\n\n // These are not actually hop-by-hop headers, but we remove them because the\n // upstream payload gets parsed and re-serialized, so content length and\n // encoding may no longer be accurate.\n result.delete('content-length')\n result.delete('content-encoding')\n\n return result\n}\n"]}
package/dist/util.d.ts CHANGED
@@ -46,4 +46,5 @@ export declare function buildAtprotoHeaders(options: {
46
46
  labelers?: Iterable<DidString>;
47
47
  }): Headers;
48
48
  export declare function toReadableStream(data: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array>;
49
+ export declare function toReadableStreamPonyfill(data: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array>;
49
50
  //# sourceMappingURL=util.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,qBAAqB,EACrB,SAAS,EACT,KAAK,EACN,MAAM,qBAAqB,CAAA;AAE5B;;;;;;;GAOG;AACH,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,GAAG,SAAS,GAAG,KAAK,IAC1E,qBAAqB,CAAC,CAAC,EAAE,UAAU,CAAC,CAAA;AAEtC;;;;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AAiB,CAAC,CAAC,EAAE,UAAU,CAAC,CAAA;AAEpC;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAexD;AAED,wBAAgB,eAAe,CAAC,CAAC,EAC/B,KAAK,EAAE,CAAC,GACP,KAAK,IAAI,OAAO,SAAS,CAAC,GACzB,CAAC,GAAG,aAAa,CAAC,OAAO,CAAC,GAC1B,OAAO,CAAC,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,CAIjC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAC3C,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,OAAO,CAAC,EAAE,GAAG,SAAS,IAAI,MAAM,EAAE,CAAA;IAClC,QAAQ,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAA;CAC/B,GAAG,OAAO,CAiBV;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,GAC9B,cAAc,CAAC,UAAU,CAAC,CAU5B;AAED,wBAAgB,wBAAwB,CACtC,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,GAC9B,cAAc,CAAC,UAAU,CAAC,CAmB5B"}
package/dist/util.js CHANGED
@@ -4,6 +4,7 @@ exports.isBlobLike = isBlobLike;
4
4
  exports.isAsyncIterable = isAsyncIterable;
5
5
  exports.buildAtprotoHeaders = buildAtprotoHeaders;
6
6
  exports.toReadableStream = toReadableStream;
7
+ exports.toReadableStreamPonyfill = toReadableStreamPonyfill;
7
8
  /**
8
9
  * Type guard to check if a value is {@link Blob}-like.
9
10
  *
@@ -59,9 +60,14 @@ function buildAtprotoHeaders(options) {
59
60
  }
60
61
  function toReadableStream(data) {
61
62
  // Use the native ReadableStream.from() if available.
63
+ /* v8 ignore next -- @preserve */
62
64
  if ('from' in ReadableStream && typeof ReadableStream.from === 'function') {
63
65
  return ReadableStream.from(data);
64
66
  }
67
+ /* v8 ignore next -- @preserve */
68
+ return toReadableStreamPonyfill(data);
69
+ }
70
+ function toReadableStreamPonyfill(data) {
65
71
  let iterator;
66
72
  return new ReadableStream({
67
73
  async pull(controller) {
package/dist/util.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAuCA,gCAeC;AAED,0CAQC;AAeD,kDAqBC;AAED,4CA0BC;AAlGD;;;;;;;;GAQG;AACH,SAAgB,UAAU,CAAC,KAAc;IACvC,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,KAAK,CAAA;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAA;IAC3C,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,IAAI,CAAA;IAEpE,yEAAyE;IACzE,qCAAqC;IACrC,4GAA4G;IAE5G,MAAM,GAAG,GAAI,KAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;IAC9C,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;QACrC,OAAO,QAAQ,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,CAAA;IAChE,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAgB,eAAe,CAC7B,KAAQ;IAIR,OAAO,CACL,KAAK,IAAI,IAAI,IAAI,OAAQ,KAAa,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,UAAU,CAC5E,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAgB,mBAAmB,CAAC,OAInC;IACC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IAE7C,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QACrD,OAAO,CAA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sourcesContent":["import {\n DidString,\n InferMethodOutput,\n InferMethodOutputBody,\n Procedure,\n Query,\n} from '@atproto/lex-schema'\n\n/**\n * The body type of an XRPC response, inferred from the method's output schema.\n *\n * For JSON responses, this is the parsed LexValue. For binary responses,\n * this is a Uint8Array.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponseBody<M extends Procedure | Query = Procedure | Query> =\n InferMethodOutputBody<M, Uint8Array>\n\n/**\n * The full payload type of an XRPC response, including body and encoding.\n *\n * Returns `null` for methods that have no output.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponsePayload<\n M extends Procedure | Query = Procedure | Query,\n> = InferMethodOutput<M, Uint8Array>\n\n/**\n * Type guard to check if a value is {@link Blob}-like.\n *\n * Handles both native Blobs and polyfilled Blob implementations\n * (e.g., fetch-blob from node-fetch).\n *\n * @param value - The value to check\n * @returns `true` if the value is a Blob or Blob-like object\n */\nexport function isBlobLike(value: unknown): value is Blob {\n if (value == null) return false\n if (typeof value !== 'object') return false\n if (typeof Blob === 'function' && value instanceof Blob) return true\n\n // Support for Blobs provided by libraries that don't use the native Blob\n // (e.g. fetch-blob from node-fetch).\n // https://github.com/node-fetch/fetch-blob/blob/a1a182e5978811407bef4ea1632b517567dda01f/index.js#L233-L244\n\n const tag = (value as any)[Symbol.toStringTag]\n if (tag === 'Blob' || tag === 'File') {\n return 'stream' in value && typeof value.stream === 'function'\n }\n\n return false\n}\n\nexport function isAsyncIterable<T>(\n value: T,\n): value is unknown extends T\n ? T & AsyncIterable<unknown>\n : Extract<T, AsyncIterable<any>> {\n return (\n value != null && typeof (value as any)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/**\n * Builds HTTP headers for AT Protocol requests.\n *\n * Adds the following headers when applicable:\n * - `atproto-proxy`: Service routing header (if service is specified)\n * - `atproto-accept-labelers`: Comma-separated list of labeler DIDs\n *\n * @param options - Header building options\n * @param options.headers - Base headers to include\n * @param options.service - Service proxy identifier\n * @param options.labelers - Labeler DIDs to request labels from\n * @returns A new Headers object with AT Protocol headers added\n */\nexport function buildAtprotoHeaders(options: {\n headers?: HeadersInit\n service?: `${DidString}#${string}`\n labelers?: Iterable<DidString>\n}): Headers {\n const headers = new Headers(options?.headers)\n\n if (options.service && !headers.has('atproto-proxy')) {\n headers.set('atproto-proxy', options.service)\n }\n\n if (options.labelers) {\n headers.set(\n 'atproto-accept-labelers',\n [...options.labelers, headers.get('atproto-accept-labelers')?.trim()]\n .filter(Boolean)\n .join(', '),\n )\n }\n\n return headers\n}\n\nexport function toReadableStream(\n data: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n // Use the native ReadableStream.from() if available.\n if ('from' in ReadableStream && typeof ReadableStream.from === 'function') {\n return ReadableStream.from(data)\n }\n\n let iterator: AsyncIterator<Uint8Array> | undefined\n return new ReadableStream({\n async pull(controller) {\n try {\n iterator ??= data[Symbol.asyncIterator]()\n const result = await iterator!.next()\n if (result.done) controller.close()\n else controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n iterator = undefined\n }\n },\n async cancel() {\n await iterator?.return?.()\n iterator = undefined\n },\n })\n}\n"]}
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAuCA,gCAeC;AAED,0CAQC;AAeD,kDAqBC;AAED,4CAYC;AAED,4DAqBC;AA3GD;;;;;;;;GAQG;AACH,SAAgB,UAAU,CAAC,KAAc;IACvC,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,KAAK,CAAA;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAA;IAC3C,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,IAAI,CAAA;IAEpE,yEAAyE;IACzE,qCAAqC;IACrC,4GAA4G;IAE5G,MAAM,GAAG,GAAI,KAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;IAC9C,IAAI,GA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,wBAAwB,CACtC,IAA+B;IAE/B,IAAI,QAA+C,CAAA;IACnD,OAAO,IAAI,cAAc,CAAC;QACxB,KAAK,CAAC,IAAI,CAAC,UAAU;YACnB,IAAI,CAAC;gBACH,QAAQ,KAAK,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;gBACzC,MAAM,MAAM,GAAG,MAAM,QAAS,CAAC,IAAI,EAAE,CAAA;gBACrC,IAAI,MAAM,CAAC,IAAI;oBAAE,UAAU,CAAC,KAAK,EAAE,CAAA;;oBAC9B,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;gBACrB,QAAQ,GAAG,SAAS,CAAA;YACtB,CAAC;QACH,CAAC;QACD,KAAK,CAAC,MAAM;YACV,MAAM,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAA;YAC1B,QAAQ,GAAG,SAAS,CAAA;QACtB,CAAC;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {\n DidString,\n InferMethodOutput,\n InferMethodOutputBody,\n Procedure,\n Query,\n} from '@atproto/lex-schema'\n\n/**\n * The body type of an XRPC response, inferred from the method's output schema.\n *\n * For JSON responses, this is the parsed LexValue. For binary responses,\n * this is a Uint8Array.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponseBody<M extends Procedure | Query = Procedure | Query> =\n InferMethodOutputBody<M, Uint8Array>\n\n/**\n * The full payload type of an XRPC response, including body and encoding.\n *\n * Returns `null` for methods that have no output.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponsePayload<\n M extends Procedure | Query = Procedure | Query,\n> = InferMethodOutput<M, Uint8Array>\n\n/**\n * Type guard to check if a value is {@link Blob}-like.\n *\n * Handles both native Blobs and polyfilled Blob implementations\n * (e.g., fetch-blob from node-fetch).\n *\n * @param value - The value to check\n * @returns `true` if the value is a Blob or Blob-like object\n */\nexport function isBlobLike(value: unknown): value is Blob {\n if (value == null) return false\n if (typeof value !== 'object') return false\n if (typeof Blob === 'function' && value instanceof Blob) return true\n\n // Support for Blobs provided by libraries that don't use the native Blob\n // (e.g. fetch-blob from node-fetch).\n // https://github.com/node-fetch/fetch-blob/blob/a1a182e5978811407bef4ea1632b517567dda01f/index.js#L233-L244\n\n const tag = (value as any)[Symbol.toStringTag]\n if (tag === 'Blob' || tag === 'File') {\n return 'stream' in value && typeof value.stream === 'function'\n }\n\n return false\n}\n\nexport function isAsyncIterable<T>(\n value: T,\n): value is unknown extends T\n ? T & AsyncIterable<unknown>\n : Extract<T, AsyncIterable<any>> {\n return (\n value != null && typeof (value as any)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/**\n * Builds HTTP headers for AT Protocol requests.\n *\n * Adds the following headers when applicable:\n * - `atproto-proxy`: Service routing header (if service is specified)\n * - `atproto-accept-labelers`: Comma-separated list of labeler DIDs\n *\n * @param options - Header building options\n * @param options.headers - Base headers to include\n * @param options.service - Service proxy identifier\n * @param options.labelers - Labeler DIDs to request labels from\n * @returns A new Headers object with AT Protocol headers added\n */\nexport function buildAtprotoHeaders(options: {\n headers?: HeadersInit\n service?: `${DidString}#${string}`\n labelers?: Iterable<DidString>\n}): Headers {\n const headers = new Headers(options?.headers)\n\n if (options.service && !headers.has('atproto-proxy')) {\n headers.set('atproto-proxy', options.service)\n }\n\n if (options.labelers) {\n headers.set(\n 'atproto-accept-labelers',\n [...options.labelers, headers.get('atproto-accept-labelers')?.trim()]\n .filter(Boolean)\n .join(', '),\n )\n }\n\n return headers\n}\n\nexport function toReadableStream(\n data: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n // Use the native ReadableStream.from() if available.\n\n /* v8 ignore next -- @preserve */\n if ('from' in ReadableStream && typeof ReadableStream.from === 'function') {\n return ReadableStream.from(data)\n }\n\n /* v8 ignore next -- @preserve */\n return toReadableStreamPonyfill(data)\n}\n\nexport function toReadableStreamPonyfill(\n data: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n let iterator: AsyncIterator<Uint8Array> | undefined\n return new ReadableStream({\n async pull(controller) {\n try {\n iterator ??= data[Symbol.asyncIterator]()\n const result = await iterator!.next()\n if (result.done) controller.close()\n else controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n iterator = undefined\n }\n },\n async cancel() {\n await iterator?.return?.()\n iterator = undefined\n },\n })\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"xrpc.d.ts","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EAEJ,MAAM,EAEN,SAAS,EACT,KAAK,EACL,UAAU,EACV,YAAY,EAEb,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,KAAK,EAAE,YAAY,EAAc,MAAM,YAAY,CAAA;AAC5D,OAAO,EAAE,WAAW,EAAiB,MAAM,aAAa,CAAA;AACxD,OAAO,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAC5C,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AASxD,KAAK,iBAAiB,CAAC,CAAC,SAAS,MAAM,IACrC,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,GAAG;IAAE,MAAM,CAAC,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,MAAM,EAAE,CAAC,CAAA;CAAE,CAAA;AAEjE;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,GAAG,YAAY,IACtE,UAAU,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAA;AAE7B,KAAK,kBAAkB,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,IAAI,CAAC,SAAS,SAAS,GACtE,YAAY,CAAC,CAAC,CAAC,OAAO,CAAC,EAAE,cAAc,CAAC,GACxC,SAAS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KAAK,CAAC,CAAC,SAAS,KAAK,GAAG,SAAS,EAC1D,SAAS,EAAE,KAAK,GAAG,YAAY,EAC/B,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EACX,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,GACtB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;AAW3B;;;;;;;GAOG;AACH,MAAM,MAAM,UAAU,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,IAC9C,YAAY,CAAC,CAAC,CAAC,GACf,WAAW,CAAC,CAAC,CAAC,CAAA;AAElB;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,QAAQ,CAAC,KAAK,CAAC,CAAC,SAAS,KAAK,GAAG,SAAS,EAC9D,SAAS,EAAE,KAAK,GAAG,YAAY,EAC/B,EAAE,EAAE,WAAW,CAAC,OAAO,CAAC,SAAS,WAAW,CAAC,CAAC,CAAC,GAC3C,IAAI,CAAC,CAAC,CAAC,GACP,UAAU,CAAC,iDAAiD,CAAC,GAChE,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA;AACzB,wBAAsB,QAAQ,CAAC,KAAK,CAAC,CAAC,SAAS,KAAK,GAAG,SAAS,EAC9D,SAAS,EAAE,KAAK,GAAG,YAAY,EAC/B,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EACX,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,GACtB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAA"}
package/dist/xrpc.js CHANGED
@@ -23,7 +23,9 @@ async function xrpcSafe(agentOpts, ns, options = {}) {
23
23
  const agent = (0, agent_js_1.buildAgent)(agentOpts);
24
24
  const url = xrpcRequestUrl(method, options);
25
25
  const request = xrpcRequestInit(method, options);
26
- const response = await agent.fetchHandler(url, request);
26
+ const response = await agent.fetchHandler(url, request).catch((cause) => {
27
+ throw new errors_js_1.XrpcFetchError(method, cause);
28
+ });
27
29
  return await response_js_1.XrpcResponse.fromFetchResponse(method, response, options);
28
30
  }
29
31
  catch (cause) {
package/dist/xrpc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"xrpc.js","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":";;AAiHA,oBAQC;AAmDD,4BAgBC;AA5LD,gDAAwE;AACxE,gDAAgD;AAChD,oDAY4B;AAC5B,yCAA4D;AAC5D,2CAAwD;AACxD,+CAA4C;AAE5C,uCAKkB;AAyFX,KAAK,UAAU,IAAI,CACxB,SAA+B,EAC/B,EAAW,EACX,UAA0B,EAAoB;IAE9C,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAI,SAAS,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;IAC1D,IAAI,QAAQ,CAAC,OAAO;QAAE,OAAO,QAAQ,CAAA;;QAChC,MAAM,QAAQ,CAAA;AACrB,CAAC;AAmDM,KAAK,UAAU,QAAQ,CAC5B,SAA+B,EAC/B,EAAW,EACX,UAA0B,EAAoB;IAE9C,OAAO,CAAC,MAAM,EAAE,cAAc,EAAE,CAAA;IAChC,MAAM,MAAM,GAAM,IAAA,oBAAO,EAAC,EAAE,CAAC,CAAA;IAC7B,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAA,qBAAU,EAAC,SAAS,CAAC,CAAA;QACnC,MAAM,GAAG,GAAG,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAC3C,MAAM,OAAO,GAAG,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;QAChD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,OAAO,CAAC,CAAA;QACvD,OAAO,MAAM,0BAAY,CAAC,iBAAiB,CAAI,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAA;IAC3E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,IAAA,yBAAa,EAAC,MAAM,EAAE,KAAK,CAAC,CAAA;I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ex-data'\nimport { lexStringify } from '@atproto/lex-json'\nimport {\n InferInput,\n InferPayload,\n Main,\n NsidString,\n Params,\n Payload,\n Procedure,\n Query,\n Restricted,\n Subscription,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure, asXrpcFailure } from './errors.js'\nimport { XrpcResponse } from './response.js'\nimport { BinaryBodyInit, CallOptions } from './types.js'\nimport {\n buildAtprotoHeaders,\n isAsyncIterable,\n isBlobLike,\n toReadableStream,\n} from './util.js'\n\n// If all params are optional, allow omitting the params object\ntype XrpcParamsOptions<P extends Params> =\n NonNullable<unknown> extends P ? { params?: P } : { params: P }\n\n/**\n * The query/path parameters type for an XRPC method, inferred from its schema.\n *\n * @typeParam M - The XRPC method type (Procedure, Query, or Subscription)\n */\nexport type XrpcRequestParams<M extends Procedure | Query | Subscription> =\n InferInput<M['parameters']>\n\ntype XrpcRequestPayload<M extends Procedure | Query> = M extends Procedure\n ? InferPayload<M['input'], BinaryBodyInit>\n : undefined\n\ntype XrpcInputOptions<In> = In extends { body: infer B; encoding: infer E }\n ? // encoding will be inferred from the schema at runtime if not provided\n { body: B; encoding?: E }\n : { body?: undefined; encoding?: undefined }\n\n/**\n * Options for making an XRPC request.\n *\n * Combines {@link CallOptions} with method-specific params and body requirements.\n * The type system ensures required params/body are provided based on the method schema.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n * @see {@link CallOptions} for general request options like signal and validateRequest\n * @see {@link XrpcParamsOptions} for method-specific query parameters\n * @see {@link XrpcInputOptions} for method-specific body and encoding requirements\n *\n * @example Query with params\n * ```typescript\n * const options: XrpcOptions<typeof app.bsky.feed.getTimeline.main> = {\n * params: { limit: 50 }\n * }\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const options: XrpcOptions<typeof com.atproto.repo.createRecord.main> = {\n * body: { repo: did, collection: 'app.bsky.feed.post', record: { ... } }\n * }\n * ```\n */\nexport type XrpcOptions<M extends Procedure | Query = Procedure | Query> =\n CallOptions &\n XrpcInputOptions<XrpcRequestPayload<M>> &\n XrpcParamsOptions<XrpcRequestParams<M>>\n\n/**\n * Makes an XRPC request and throws on failure.\n *\n * This is the low-level function for making XRPC calls.\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns The successful {@link XrpcResponse}\n * @throws {XrpcFailure} When the request fails\n *\n * @example\n * ```typescript\n * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {\n * params: { handle: \"atproto.com\" }\n * })\n * ```\n *\n * @example\n * ```typescript\n * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResponse<M>> {\n const response = await xrpcSafe<M>(agentOpts, ns, options)\n if (response.success) return response\n else throw response\n}\n\n/**\n * Union type representing either a successful response or a failure.\n *\n * Both {@link XrpcResponse} and {@link XrpcFailure} have a `success` property\n * that can be used to discriminate between them.\n *\n * @typeParam M - The XRPC method type\n */\nexport type XrpcResult<M extends Procedure | Query> =\n | XrpcResponse<M>\n | XrpcFailure<M>\n\n/**\n * Makes an XRPC request without throwing on failure.\n *\n * Returns a discriminated union that can be checked via the `success` property.\n * This is useful for handling errors without try/catch blocks. This also allow\n * failure results to be typed with the method schema, which can provide better\n * type safety when handling errors (e.g. checking for specific error codes).\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns Either a successful {@link XrpcResponse} or an {@link XrpcFailure}\n *\n * @example\n * ```typescript\n * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Request failed:', result.error)\n * }\n * ```\n */\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResult<M>> {\n options.signal?.throwIfAborted()\n const method: M = getMain(ns)\n try {\n const agent = buildAgent(agentOpts)\n const url = xrpcRequestUrl(method, options)\n const request = xrpcRequestInit(method, options)\n const response = await agent.fetchHandler(url, request)\n return await XrpcResponse.fromFetchResponse<M>(method, response, options)\n } catch (cause) {\n return asXrpcFailure(method, cause)\n }\n}\n\nfunction xrpcRequestUrl<M extends Procedure | Query | Subscription>(\n method: M,\n options: CallOptions & { params?: Params },\n): `/xrpc/${NsidString}${'' | `?${string}`}` {\n const path = `/xrpc/${method.nsid}` as const\n\n const queryString = method.parameters\n ?.toURLSearchParams(options.params ?? {})\n .toString()\n\n return queryString ? (`${path}?${queryString}` as const) : path\n}\n\nfunction xrpcRequestInit<T extends Procedure | Query>(\n schema: T,\n options: CallOptions & {\n body?: LexValue | BinaryBodyInit\n encoding?: string\n },\n): RequestInit & { duplex?: 'half' } {\n const headers = buildAtprotoHeaders(options)\n\n // Tell the server what type of response we're expecting\n if (schema.output.encoding) {\n headers.set('accept', schema.output.encoding)\n }\n\n // Caller should not set content-type header\n if (headers.has('content-type')) {\n const contentType = headers.get('content-type')\n throw new TypeError(`Unexpected content-type header (${contentType})`)\n }\n\n // Requests with body\n if ('input' in schema) {\n const encodingHint = options.encoding\n const input = xrpcProcedureInput(schema, options, encodingHint)\n\n if (input) {\n headers.set('content-type', input.encoding)\n } else if (encodingHint != null) {\n throw new TypeError(`Unexpected encoding hint (${encodingHint})`)\n }\n\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'POST',\n headers,\n body: input?.body,\n }\n }\n\n // Requests without body\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'GET',\n headers,\n }\n}\n\nfunction xrpcProcedureInput(\n method: Procedure,\n options: CallOptions & { body?: LexValue | BinaryBodyInit },\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n const { input } = method\n const { body } = options\n\n if (options.validateRequest) {\n input.schema?.check(body)\n }\n\n // Special handling for endpoints expecting application/json input\n if (input.encoding === 'application/json') {\n // @NOTE **NOT** using isLexValue here to avoid deep checks in order to\n // distinguish between LexValue and BinaryBodyInit.\n if (!isLexScalar(body) && !isPlainObject(body) && !Array.isArray(body)) {\n throw new TypeError(`Expected LexValue body, got ${typeof body}`)\n }\n\n return buildPayload(input, lexStringify(body), encodingHint)\n }\n\n // Other encodings will be sent unaltered (ie. as binary data)\n switch (typeof body) {\n case 'undefined':\n case 'string':\n return buildPayload(input, body, encodingHint)\n case 'object': {\n if (body === null) break\n if (\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof ReadableStream\n ) {\n return buildPayload(input, body, encodingHint)\n } else if (isAsyncIterable(body)) {\n return buildPayload(input, toReadableStream(body), encodingHint)\n } else if (isBlobLike(body)) {\n return buildPayload(input, body, encodingHint || body.type)\n }\n }\n }\n\n throw new TypeError(\n `Invalid ${typeof body} body for ${input.encoding} encoding`,\n )\n}\n\nfunction buildPayload(\n schema: Payload,\n body: undefined | BodyInit,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n if (schema.encoding === undefined) {\n if (body !== undefined) {\n throw new TypeError(\n `Cannot send a ${typeof body} body with undefined encoding`,\n )\n }\n\n return null\n }\n\n if (body === undefined) {\n // This error would be returned by the server, but we can catch it earlier\n // to avoid un-necessary requests. Note that a content-length of 0 does not\n // necessary mean that the body is \"empty\" (e.g. an empty txt file).\n throw new TypeError(`A request body is expected but none was provided`)\n }\n\n const encoding = buildEncoding(schema, encodingHint)\n return { encoding, body }\n}\n\nfunction buildEncoding(schema: Payload, encodingHint?: string): string {\n // Should never happen (required for type safety)\n if (!schema.encoding) {\n throw new TypeError('Unexpected payload')\n }\n\n if (encodingHint?.length) {\n if (!schema.matchesEncoding(encodingHint)) {\n throw new TypeError(\n `Cannot send a body with content-type \"${encodingHint}\" for \"${schema.encoding}\" encoding`,\n )\n }\n return encodingHint\n }\n\n // Fallback\n\n if (schema.encoding === '*/*') {\n return 'application/octet-stream'\n }\n\n if (schema.encoding.startsWith('text/')) {\n return schema.encoding.includes('*')\n ? 'text/plain; charset=utf-8'\n : `${schema.encoding}; charset=utf-8`\n }\n\n if (!schema.encoding.includes('*')) {\n return schema.encoding\n }\n\n throw new TypeError(\n `Unable to determine payload encoding. Please provide a 'content-type' header matching ${schema.encoding}.`,\n )\n}\n"]}
1
+ {"version":3,"file":"xrpc.js","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":";;AAiHA,oBAQC;AAmDD,4BAkBC;AA9LD,gDAAwE;AACxE,gDAAgD;AAChD,oDAY4B;AAC5B,yCAA4D;AAC5D,2CAAwE;AACxE,+CAA4C;AAE5C,uCAKkB;AAyFX,KAAK,UAAU,IAAI,C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AAC3B,CAAC;AAED,SAAS,aAAa,CAAC,MAAe,EAAE,YAAqB;IAC3D,iDAAiD;IACjD,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;QACrB,MAAM,IAAI,SAAS,CAAC,oBAAoB,CAAC,CAAA;IAC3C,CAAC;IAED,IAAI,YAAY,EAAE,MAAM,EAAE,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,SAAS,CACjB,yCAAyC,YAAY,UAAU,MAAM,CAAC,QAAQ,YAAY,CAC3F,CAAA;QACH,CAAC;QACD,OAAO,YAAY,CAAA;IACrB,CAAC;IAED,WAAW;IAEX,IAAI,MAAM,CAAC,QAAQ,KAAK,KAAK,EAAE,CAAC;QAC9B,OAAO,0BAA0B,CAAA;IACnC,CAAC;IAED,IAAI,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QACxC,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;YAClC,CAAC,CAAC,2BAA2B;YAC7B,CAAC,CAAC,GAAG,MAAM,CAAC,QAAQ,iBAAiB,CAAA;IACzC,CAAC;IAED,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACnC,OAAO,MAAM,CAAC,QAAQ,CAAA;IACxB,CAAC;IAED,MAAM,IAAI,SAAS,CACjB,yFAAyF,MAAM,CAAC,QAAQ,GAAG,CAC5G,CAAA;AACH,CAAC","sourcesContent":["import { LexValue, isLexScalar, isPlainObject } from '@atproto/lex-data'\nimport { lexStringify } from '@atproto/lex-json'\nimport {\n InferInput,\n InferPayload,\n Main,\n NsidString,\n Params,\n Payload,\n Procedure,\n Query,\n Restricted,\n Subscription,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure, XrpcFetchError, asXrpcFailure } from './errors.js'\nimport { XrpcResponse } from './response.js'\nimport { BinaryBodyInit, CallOptions } from './types.js'\nimport {\n buildAtprotoHeaders,\n isAsyncIterable,\n isBlobLike,\n toReadableStream,\n} from './util.js'\n\n// If all params are optional, allow omitting the params object\ntype XrpcParamsOptions<P extends Params> =\n NonNullable<unknown> extends P ? { params?: P } : { params: P }\n\n/**\n * The query/path parameters type for an XRPC method, inferred from its schema.\n *\n * @typeParam M - The XRPC method type (Procedure, Query, or Subscription)\n */\nexport type XrpcRequestParams<M extends Procedure | Query | Subscription> =\n InferInput<M['parameters']>\n\ntype XrpcRequestPayload<M extends Procedure | Query> = M extends Procedure\n ? InferPayload<M['input'], BinaryBodyInit>\n : undefined\n\ntype XrpcInputOptions<In> = In extends { body: infer B; encoding: infer E }\n ? // encoding will be inferred from the schema at runtime if not provided\n { body: B; encoding?: E }\n : { body?: undefined; encoding?: undefined }\n\n/**\n * Options for making an XRPC request.\n *\n * Combines {@link CallOptions} with method-specific params and body requirements.\n * The type system ensures required params/body are provided based on the method schema.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n * @see {@link CallOptions} for general request options like signal and validateRequest\n * @see {@link XrpcParamsOptions} for method-specific query parameters\n * @see {@link XrpcInputOptions} for method-specific body and encoding requirements\n *\n * @example Query with params\n * ```typescript\n * const options: XrpcOptions<typeof app.bsky.feed.getTimeline.main> = {\n * params: { limit: 50 }\n * }\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const options: XrpcOptions<typeof com.atproto.repo.createRecord.main> = {\n * body: { repo: did, collection: 'app.bsky.feed.post', record: { ... } }\n * }\n * ```\n */\nexport type XrpcOptions<M extends Procedure | Query = Procedure | Query> =\n CallOptions &\n XrpcInputOptions<XrpcRequestPayload<M>> &\n XrpcParamsOptions<XrpcRequestParams<M>>\n\n/**\n * Makes an XRPC request and throws on failure.\n *\n * This is the low-level function for making XRPC calls.\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns The successful {@link XrpcResponse}\n * @throws {XrpcFailure} When the request fails\n *\n * @example\n * ```typescript\n * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {\n * params: { handle: \"atproto.com\" }\n * })\n * ```\n *\n * @example\n * ```typescript\n * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResponse<M>> {\n const response = await xrpcSafe<M>(agentOpts, ns, options)\n if (response.success) return response\n else throw response\n}\n\n/**\n * Union type representing either a successful response or a failure.\n *\n * Both {@link XrpcResponse} and {@link XrpcFailure} have a `success` property\n * that can be used to discriminate between them.\n *\n * @typeParam M - The XRPC method type\n */\nexport type XrpcResult<M extends Procedure | Query> =\n | XrpcResponse<M>\n | XrpcFailure<M>\n\n/**\n * Makes an XRPC request without throwing on failure.\n *\n * Returns a discriminated union that can be checked via the `success` property.\n * This is useful for handling errors without try/catch blocks. This also allow\n * failure results to be typed with the method schema, which can provide better\n * type safety when handling errors (e.g. checking for specific error codes).\n *\n * @param agent - The {@link Agent} to use for making the request\n * @param ns - The lexicon method definition\n * @param options - Request {@link XrpcOptions options} (params, body, headers, etc.)\n * @returns Either a successful {@link XrpcResponse} or an {@link XrpcFailure}\n *\n * @example\n * ```typescript\n * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Request failed:', result.error)\n * }\n * ```\n */\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agentOpts: Agent | AgentOptions,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResult<M>> {\n options.signal?.throwIfAborted()\n const method: M = getMain(ns)\n try {\n const agent = buildAgent(agentOpts)\n const url = xrpcRequestUrl(method, options)\n const request = xrpcRequestInit(method, options)\n const response = await agent.fetchHandler(url, request).catch((cause) => {\n throw new XrpcFetchError(method, cause)\n })\n return await XrpcResponse.fromFetchResponse<M>(method, response, options)\n } catch (cause) {\n return asXrpcFailure(method, cause)\n }\n}\n\nfunction xrpcRequestUrl<M extends Procedure | Query | Subscription>(\n method: M,\n options: CallOptions & { params?: Params },\n): `/xrpc/${NsidString}${'' | `?${string}`}` {\n const path = `/xrpc/${method.nsid}` as const\n\n const queryString = method.parameters\n ?.toURLSearchParams(options.params ?? {})\n .toString()\n\n return queryString ? (`${path}?${queryString}` as const) : path\n}\n\nfunction xrpcRequestInit<T extends Procedure | Query>(\n schema: T,\n options: CallOptions & {\n body?: LexValue | BinaryBodyInit\n encoding?: string\n },\n): RequestInit & { duplex?: 'half' } {\n const headers = buildAtprotoHeaders(options)\n\n // Tell the server what type of response we're expecting\n if (schema.output.encoding) {\n headers.set('accept', schema.output.encoding)\n }\n\n // Caller should not set content-type header\n if (headers.has('content-type')) {\n const contentType = headers.get('content-type')\n throw new TypeError(`Unexpected content-type header (${contentType})`)\n }\n\n // Requests with body\n if ('input' in schema) {\n const encodingHint = options.encoding\n const input = xrpcProcedureInput(schema, options, encodingHint)\n\n if (input) {\n headers.set('content-type', input.encoding)\n } else if (encodingHint != null) {\n throw new TypeError(`Unexpected encoding hint (${encodingHint})`)\n }\n\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'POST',\n headers,\n body: input?.body,\n }\n }\n\n // Requests without body\n return {\n duplex: 'half',\n redirect: 'follow',\n referrerPolicy: 'strict-origin-when-cross-origin', // (default)\n mode: 'cors', // (default)\n signal: options.signal,\n method: 'GET',\n headers,\n }\n}\n\nfunction xrpcProcedureInput(\n method: Procedure,\n options: CallOptions & { body?: LexValue | BinaryBodyInit },\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n const { input } = method\n const { body } = options\n\n if (options.validateRequest) {\n input.schema?.check(body)\n }\n\n // Special handling for endpoints expecting application/json input\n if (input.encoding === 'application/json') {\n // @NOTE **NOT** using isLexValue here to avoid deep checks in order to\n // distinguish between LexValue and BinaryBodyInit.\n if (!isLexScalar(body) && !isPlainObject(body) && !Array.isArray(body)) {\n throw new TypeError(`Expected LexValue body, got ${typeof body}`)\n }\n\n return buildPayload(input, lexStringify(body), encodingHint)\n }\n\n // Other encodings will be sent unaltered (ie. as binary data)\n switch (typeof body) {\n case 'undefined':\n case 'string':\n return buildPayload(input, body, encodingHint)\n case 'object': {\n if (body === null) break\n if (\n ArrayBuffer.isView(body) ||\n body instanceof ArrayBuffer ||\n body instanceof ReadableStream\n ) {\n return buildPayload(input, body, encodingHint)\n } else if (isAsyncIterable(body)) {\n return buildPayload(input, toReadableStream(body), encodingHint)\n } else if (isBlobLike(body)) {\n return buildPayload(input, body, encodingHint || body.type)\n }\n }\n }\n\n throw new TypeError(\n `Invalid ${typeof body} body for ${input.encoding} encoding`,\n )\n}\n\nfunction buildPayload(\n schema: Payload,\n body: undefined | BodyInit,\n encodingHint?: string,\n): null | { body: BodyInit; encoding: string } {\n if (schema.encoding === undefined) {\n if (body !== undefined) {\n throw new TypeError(\n `Cannot send a ${typeof body} body with undefined encoding`,\n )\n }\n\n return null\n }\n\n if (body === undefined) {\n // This error would be returned by the server, but we can catch it earlier\n // to avoid un-necessary requests. Note that a content-length of 0 does not\n // necessary mean that the body is \"empty\" (e.g. an empty txt file).\n throw new TypeError(`A request body is expected but none was provided`)\n }\n\n const encoding = buildEncoding(schema, encodingHint)\n return { encoding, body }\n}\n\nfunction buildEncoding(schema: Payload, encodingHint?: string): string {\n // Should never happen (required for type safety)\n if (!schema.encoding) {\n throw new TypeError('Unexpected payload')\n }\n\n if (encodingHint?.length) {\n if (!schema.matchesEncoding(encodingHint)) {\n throw new TypeError(\n `Cannot send a body with content-type \"${encodingHint}\" for \"${schema.encoding}\" encoding`,\n )\n }\n return encodingHint\n }\n\n // Fallback\n\n if (schema.encoding === '*/*') {\n return 'application/octet-stream'\n }\n\n if (schema.encoding.startsWith('text/')) {\n return schema.encoding.includes('*')\n ? 'text/plain; charset=utf-8'\n : `${schema.encoding}; charset=utf-8`\n }\n\n if (!schema.encoding.includes('*')) {\n return schema.encoding\n }\n\n throw new TypeError(\n `Unable to determine payload encoding. Please provide a 'content-type' header matching ${schema.encoding}.`,\n )\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-client",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "license": "MIT",
5
5
  "description": "HTTP client for interacting with Lexicon based APIs",
6
6
  "keywords": [
@@ -39,12 +39,12 @@
39
39
  "tslib": "^2.8.1",
40
40
  "@atproto/lex-data": "^0.0.13",
41
41
  "@atproto/lex-json": "^0.0.13",
42
- "@atproto/lex-schema": "^0.0.14"
42
+ "@atproto/lex-schema": "^0.0.15"
43
43
  },
44
44
  "devDependencies": {
45
45
  "vitest": "^4.0.16",
46
46
  "@atproto/lex-cbor": "^0.0.14",
47
- "@atproto/lex-builder": "^0.0.17"
47
+ "@atproto/lex-builder": "^0.0.18"
48
48
  },
49
49
  "scripts": {
50
50
  "prebuild": "node ./scripts/lex-build.mjs",