@atproto/lex-client 0.0.13 → 0.0.14

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,11 @@
1
1
  # @atproto/lex-client
2
2
 
3
+ ## 0.0.14
4
+
5
+ ### Patch Changes
6
+
7
+ - [#4672](https://github.com/bluesky-social/atproto/pull/4672) [`38852f0`](https://github.com/bluesky-social/atproto/commit/38852f0ddfa9fbce8036233dc6af87614e9ae4b2) Thanks [@matthieusieben](https://github.com/matthieusieben)! - Allow calling `xrpc` and `xrpcSafe` functions with a service URL
8
+
3
9
  ## 0.0.13
4
10
 
5
11
  ### Patch Changes
package/dist/agent.d.ts CHANGED
@@ -4,7 +4,7 @@ import { DidString } from '@atproto/lex-schema';
4
4
  *
5
5
  * The handler is responsible for adding the origin (protocol, hostname, and
6
6
  * port) to the provided path, typically based on authentication or service
7
- * configuration. The handler are also responsible for adding any necessary
7
+ * configuration. The handler can also be responsible for adding any necessary
8
8
  * headers, such as authorization tokens.
9
9
  *
10
10
  * @param path - The URL path (pathname + query parameters) without the origin
@@ -17,13 +17,20 @@ export type FetchHandler = (
17
17
  * origin. The origin (protocol, hostname, and port) must be added by this
18
18
  * {@link FetchHandler}, typically based on authentication or other factors.
19
19
  */
20
- path: string, init: RequestInit) => Promise<Response>;
20
+ path: `/${string}`, init: RequestInit) => Promise<Response>;
21
21
  /**
22
- * Core interface for making XRPC requests.
22
+ * Core interface for making XRPC requests towards a specific service.
23
23
  *
24
- * An Agent encapsulates an identity and request handling for AT Protocol
25
- * operations. It can represent an authenticated user session or an
26
- * unauthenticated service client.
24
+ * An {@link Agent} encapsulates an identity and request handling for AT
25
+ * Protocol operations. Agents will typically handle authentication, service URL
26
+ * resolution, and other request configuration, allowing client code to make
27
+ * requests without needing to manage these details directly. The key component
28
+ * of an Agent is the {@link FetchHandler}, which is responsible for
29
+ * constructing the full request URL and adding any necessary headers or
30
+ * authentication tokens. The Agent's `did` property represents the
31
+ * authenticated user's DID, if available, and can be used for operations that
32
+ * require knowledge of the user's identity (such as creating AT Protocol
33
+ * records).
27
34
  *
28
35
  * @see {@link buildAgent} for creating (simple) Agent instances.
29
36
  *
@@ -31,7 +38,10 @@ path: string, init: RequestInit) => Promise<Response>;
31
38
  * ```typescript
32
39
  * const agent: Agent = {
33
40
  * did: 'did:plc:example123',
34
- * fetchHandler: (path, init) => fetch(new URL(path, 'https://bsky.social'), init)
41
+ * fetchHandler: async (path, init) => {
42
+ * const url = new URL(path, 'https://bsky.social')
43
+ * return fetch(url, init)
44
+ * }
35
45
  * }
36
46
  * ```
37
47
  */
@@ -41,6 +51,7 @@ export interface Agent {
41
51
  /** The fetch handler used to make HTTP requests. */
42
52
  fetchHandler: FetchHandler;
43
53
  }
54
+ export declare function isAgent(value: unknown): value is Agent;
44
55
  export type AgentConfig = {
45
56
  /**
46
57
  * The identifier (DID) of the user represented by this agent.
@@ -74,20 +85,20 @@ export type AgentOptions = AgentConfig | string | URL;
74
85
  /**
75
86
  * Creates an {@link Agent} from various input types.
76
87
  *
77
- * This factory function accepts an existing Agent (returned as-is), a service URL,
78
- * or a full configuration object. It handles the common case of creating an
79
- * unauthenticated agent from just a service URL.
88
+ * This factory function accepts an existing Agent (returned as-is), a service
89
+ * URL, or a full configuration object. It handles the common case of creating
90
+ * an unauthenticated agent from just a service URL.
80
91
  *
81
92
  * @param options - Agent instance, configuration object, or service URL
82
93
  * @returns A configured Agent ready for making requests
83
94
  * @throws {TypeError} If fetch() is not available in the environment
84
95
  *
85
- * @example From URL string
96
+ * @example // From URL string
86
97
  * ```typescript
87
98
  * const agent = buildAgent('https://public.api.bsky.app')
88
99
  * ```
89
100
  *
90
- * @example From configuration
101
+ * @example // From configuration
91
102
  * ```typescript
92
103
  * const agent = buildAgent({
93
104
  * did: 'did:plc:example',
@@ -95,12 +106,6 @@ export type AgentOptions = AgentConfig | string | URL;
95
106
  * headers: { 'Authorization': 'Bearer ...' }
96
107
  * })
97
108
  * ```
98
- *
99
- * @example Pass-through existing agent
100
- * ```typescript
101
- * const existing: Agent = { ... }
102
- * const agent = buildAgent(existing) // Returns existing unchanged
103
- * ```
104
109
  */
105
- export declare function buildAgent(options: Agent | AgentOptions): Agent;
110
+ export declare function buildAgent<O extends Agent | AgentOptions>(options: O): O extends Agent ? O : Agent;
106
111
  //# sourceMappingURL=agent.d.ts.map
@@ -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,MAAM,EACZ,IAAI,EAAE,WAAW,KACd,OAAO,CAAC,QAAQ,CAAC,CAAA;AAEtB;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,WAAW,KAAK;IACpB,4EAA4E;IAC5E,QAAQ,CAAC,GAAG,CAAC,EAAE,SAAS,CAAA;IACxB,oDAAoD;IACpD,YAAY,EAAE,YAAY,CAAA;CAC3B;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,KAAK,GAAG,YAAY,GAAG,KAAK,CAiC/D"}
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"}
package/dist/agent.js CHANGED
@@ -1,41 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAgent = isAgent;
3
4
  exports.buildAgent = buildAgent;
4
- /**
5
- * Creates an {@link Agent} from various input types.
6
- *
7
- * This factory function accepts an existing Agent (returned as-is), a service URL,
8
- * or a full configuration object. It handles the common case of creating an
9
- * unauthenticated agent from just a service URL.
10
- *
11
- * @param options - Agent instance, configuration object, or service URL
12
- * @returns A configured Agent ready for making requests
13
- * @throws {TypeError} If fetch() is not available in the environment
14
- *
15
- * @example From URL string
16
- * ```typescript
17
- * const agent = buildAgent('https://public.api.bsky.app')
18
- * ```
19
- *
20
- * @example From configuration
21
- * ```typescript
22
- * const agent = buildAgent({
23
- * did: 'did:plc:example',
24
- * service: 'https://bsky.social',
25
- * headers: { 'Authorization': 'Bearer ...' }
26
- * })
27
- * ```
28
- *
29
- * @example Pass-through existing agent
30
- * ```typescript
31
- * const existing: Agent = { ... }
32
- * const agent = buildAgent(existing) // Returns existing unchanged
33
- * ```
34
- */
5
+ function isAgent(value) {
6
+ return (typeof value === 'object' &&
7
+ value !== null &&
8
+ 'fetchHandler' in value &&
9
+ typeof value.fetchHandler === 'function' &&
10
+ (!('did' in value) ||
11
+ value.did === undefined ||
12
+ typeof value.did === 'string'));
13
+ }
35
14
  function buildAgent(options) {
36
- if (typeof options === 'object' && 'fetchHandler' in options) {
15
+ if (isAgent(options))
37
16
  return options;
38
- }
39
17
  const config = typeof options === 'string' || options instanceof URL
40
18
  ? { did: undefined, service: options }
41
19
  : options;
package/dist/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;AAkHA,gCAiCC;AAhED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,SAAgB,UAAU,CAAC,OAA6B;IACtD,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,cAAc,IAAI,OAAO,EAAE,CAAC;QAC7D,OAAO,OAAO,CAAA;IAChB,CAAC;IAED,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,C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esContent":["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 are also 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.\n *\n * An Agent encapsulates an identity and request handling for AT Protocol\n * operations. It can represent an authenticated user session or an\n * unauthenticated service client.\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: (path, init) => fetch(new URL(path, 'https://bsky.social'), init)\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 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 URL,\n * or a full configuration object. It handles the common case of creating an\n * 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 *\n * @example Pass-through existing agent\n * ```typescript\n * const existing: Agent = { ... }\n * const agent = buildAgent(existing) // Returns existing unchanged\n * ```\n */\nexport function buildAgent(options: Agent | AgentOptions): Agent {\n if (typeof options === 'object' && 'fetchHandler' in options) {\n return options\n }\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,gCA+BC;AA1GD,SAAgB,OAAO,CAAC,KAAc;I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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"]}
package/dist/client.d.ts CHANGED
@@ -194,11 +194,12 @@ export type ListRecord<Value extends LexMap> = com.atproto.repo.listRecords.Reco
194
194
  * services. It provides type-safe methods for XRPC calls, record operations,
195
195
  * and blob handling.
196
196
  *
197
- * @example Basic usage
197
+ * @example // Basic usage
198
198
  * ```typescript
199
199
  * import { Client } from '@atproto/lex'
200
200
  *
201
- * const client = new Client(agent)
201
+ * const client = new Client(oauthSession)
202
+ *
202
203
  * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {
203
204
  * params: { limit: 50 }
204
205
  * })
@@ -261,11 +262,15 @@ export declare class Client implements Agent {
261
262
  */
262
263
  clearLabelers(): void;
263
264
  /**
264
- * Low-level fetch handler for making requests.
265
+ * {@link Agent}'s {@link Agent.fetchHandler} implementation, which adds
266
+ * labelers and service proxying headers. This method allow a {@link Client}
267
+ * instance to be used directly as an {@link Agent} for another
268
+ * {@link Client}, enabling composition of headers (labelers, proxying, etc.).
269
+ *
265
270
  * @param path - The request path
266
271
  * @param init - Request initialization options
267
272
  */
268
- fetchHandler(path: string, init: RequestInit): Promise<Response>;
273
+ fetchHandler(path: `/${string}`, init: RequestInit): Promise<Response>;
269
274
  /**
270
275
  * Makes an XRPC request. Throws on failure.
271
276
  *
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAC3E,OAAO,EACL,kBAAkB,EAClB,SAAS,EACT,SAAS,EACT,KAAK,EACL,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,EACd,gBAAgB,EAChB,IAAI,EACJ,UAAU,EACV,MAAM,EACN,SAAS,EACT,KAAK,EACL,YAAY,EACZ,UAAU,EAEX,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,KAAK,EAAE,YAAY,EAAc,MAAM,YAAY,CAAA;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,GAAG,EAAE,MAAM,qBAAqB,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AAC9D,OAAO,EAAE,cAAc,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAEjE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAkB,MAAM,WAAW,CAAA;AAE1E,YAAY,EACV,kBAAkB,EAClB,SAAS,EACT,SAAS,EACT,KAAK,EACL,oBAAoB,EACpB,qBAAqB,EACrB,cAAc,EACd,MAAM,EACN,QAAQ,EACR,gBAAgB,EAChB,IAAI,EACJ,UAAU,EACV,MAAM,EACN,SAAS,EACT,KAAK,EACL,YAAY,EACZ,UA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AC,EAAE,UAAU,CAAC,CAAC,CAAC,GACtB,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IAcxB;;;;;;;OAOG;IACU,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,YAAY,EAC3C,EAAE,EAAE,WAAW,CAAC,OAAO,CAAC,SAAS,UAAU,CAAC,CAAC,CAAC,GAC1C,IAAI,CAAC,CAAC,CAAC,GACP,UAAU,CAAC,iDAAiD,CAAC,EACjE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,GAC7B,OAAO,CAAC,SAAS,CAAC;IACR,GAAG,CAAC,KAAK,CAAC,CAAC,SAAS,YAAY,EAC3C,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EACX,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,EAC9B,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB,OAAO,CAAC,SAAS,CAAC;IAarB;;;;;;;;;;;;;OAaG;IACG,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,YAAY,EACrC,EAAE,EAAE,IAAI,CAAC,CAAC,CAAC,EACX,OAAO,CAAC,EAAE,WAAW,GACpB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;CAkB1B"}
package/dist/client.js CHANGED
@@ -12,11 +12,12 @@ const xrpc_js_1 = require("./xrpc.js");
12
12
  * services. It provides type-safe methods for XRPC calls, record operations,
13
13
  * and blob handling.
14
14
  *
15
- * @example Basic usage
15
+ * @example // Basic usage
16
16
  * ```typescript
17
17
  * import { Client } from '@atproto/lex'
18
18
  *
19
- * const client = new Client(agent)
19
+ * const client = new Client(oauthSession)
20
+ *
20
21
  * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {
21
22
  * params: { limit: 50 }
22
23
  * })
@@ -99,7 +100,11 @@ class Client {
99
100
  this.labelers.clear();
100
101
  }
101
102
  /**
102
- * Low-level fetch handler for making requests.
103
+ * {@link Agent}'s {@link Agent.fetchHandler} implementation, which adds
104
+ * labelers and service proxying headers. This method allow a {@link Client}
105
+ * instance to be used directly as an {@link Agent} for another
106
+ * {@link Client}, enabling composition of headers (labelers, proxying, etc.).
107
+ *
103
108
  * @param path - The request path
104
109
  * @param init - Request initialization options
105
110
  */
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,gDAA2E;AAC3E,oDAiB4B;AAC5B,yCAA4D;AAE5D,kDAAyC;AAGzC,uCAA+C;AAC/C,uCAA0E;AA8P1E;;;;;;;;;;;;;;GAcG;AACH,MAAa,MAAM;IACjB,MAAM,CAAC,WAAW,GAAyB,EAAE,CAAA;IAE7C;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,IAA2C;QAC1D,IAAI,IAAI,CAAC,WAAW;YAAE,IAAI,CAAC,WAAW,GAAG,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,CAAA;IAChE,CAAC;IAED,qDAAqD;IACrC,KAAK,CAAO;IAE5B,+CAA+C;IAC/B,OAAO,CAAS;IAEhC,wDAAwD;IACxC,OAAO,CAAU;IAEjC,4DAA4D;IAC5C,QAAQ,CAAgB;IAExC,YAAY,KAA2B,EAAE,UAAyB,EAAE;QAClE,IAAI,CAAC,KAAK,GAAG,IAAA,qBAAU,EAAC,KAAK,CAAC,CAAA;QAC9B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAA;QAC9B,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;QACzC,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAA;IAC7C,CAAC;IAED;;OAEG;IACH,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAA;IACvB,CAAC;IAED;;;OAGG;IACH,IAAI,SAAS;QACX,IAAI,C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,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAA;YAClD,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAC5B,CAAC;QACH,CAAC;QAED,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA;IACtC,CAAC;;AAxnBH,wBAynBC;AAED,SAAS,mBAAmB,CAC1B,MAAS;IAET,kCAAkC;IAClC,IAAI,MAAM,CAAC,GAAG,KAAK,KAAK;QAAE,OAAO,SAAS,CAAA;IAC1C,IAAI,MAAM,CAAC,GAAG,KAAK,KAAK;QAAE,OAAO,SAAS,CAAA;IAE1C,OAAO,mBAAmB,CAAC,MAAM,CAAC,CAAA;AACpC,CAAC;AAED,SAAS,mBAAmB,CAC1B,MAAS;IAET,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QACtC,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAsB,CAAA;IACjD,CAAC;IAED,MAAM,IAAI,SAAS,CACjB,mDAAmD,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,KAAK,GAAG,CACnF,CAAA;AACH,CAAC","sourcesContent":["import { LexError, LexMap, LexValue, TypedLexMap } from '@atproto/lex-data'\nimport {\n AtIdentifierString,\n CidString,\n DidString,\n Infer,\n InferMethodInputBody,\n InferMethodOutputBody,\n InferRecordKey,\n LexiconRecordKey,\n Main,\n NsidString,\n Params,\n Procedure,\n Query,\n RecordSchema,\n Restricted,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure } from './errors.js'\nimport { com } from './lexicons/index.js'\nimport { XrpcResponse, XrpcResponseBody } from './response.js'\nimport { BinaryBodyInit, CallOptions, Service } from './types.js'\nimport { buildAtprotoHeaders } from './util.js'\nimport { XrpcOptions, XrpcRequestParams, xrpc, xrpcSafe } from './xrpc.js'\n\nexport type {\n AtIdentifierString,\n CidString,\n DidString,\n Infer,\n InferMethodInputBody,\n InferMethodOutputBody,\n InferRecordKey,\n LexMap,\n LexValue,\n LexiconRecordKey,\n Main,\n NsidString,\n Params,\n Procedure,\n Query,\n RecordSchema,\n Restricted,\n TypedLexMap,\n}\n\n/**\n * Configuration options for creating a {@link Client}.\n *\n * @example\n * ```typescript\n * const options: ClientOptions = {\n * labelers: ['did:plc:labeler1'],\n * service: 'did:web:api.bsky.app#bsky_appview',\n * headers: { 'X-Custom-Header': 'value' }\n * }\n * ```\n */\nexport type ClientOptions = {\n /** Labeler DIDs to include in requests for content moderation. */\n labelers?: Iterable<DidString>\n /** Custom headers to include in all requests made by this client. */\n headers?: HeadersInit\n /** Service proxy identifier for routing requests through a specific service. */\n service?: Service\n}\n\n/**\n * A composable action that can be invoked via {@link Client.call}.\n *\n * Actions provide a way to define custom operations that integrate with the\n * Client's call interface, enabling type-safe, reusable business logic.\n *\n * @typeParam I - The input type for the action\n * @typeParam O - The output type for the action\n *\n * @example\n * ```typescript\n * const myAction: Action<{ userId: string }, { profile: Profile }> = async (client, input, options) => {\n * const response = await client.xrpc(someMethod, { params: { actor: input.userId }, ...options })\n * return { profile: response.body }\n * }\n * ```\n */\nexport type Action<I = any, O = any> = (\n client: Client,\n input: I,\n options: CallOptions,\n) => O | Promise<O>\n\n/**\n * Extracts the input type from an {@link Action}.\n * @typeParam A - The Action type to extract from\n */\nexport type InferActionInput<A extends Action> =\n A extends Action<infer I, any> ? I : never\n\n/**\n * Extracts the output type from an {@link Action}.\n * @typeParam A - The Action type to extract from\n */\nexport type InferActionOutput<A extends Action> =\n A extends Action<any, infer O> ? O : never\n\n/**\n * Options for creating a record in an AT Protocol repository.\n *\n * @see {@link Client.createRecord}\n */\nexport type CreateRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Whether to validate the record against its lexicon schema. */\n validate?: boolean\n}\n\n/**\n * Options for deleting a record from an AT Protocol repository.\n *\n * @see {@link Client.deleteRecord}\n */\nexport type DeleteRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Compare-and-swap on the record CID. If specified, must match current record. */\n swapRecord?: string\n}\n\n/**\n * Options for retrieving a record from an AT Protocol repository.\n *\n * @see {@link Client.getRecord}\n */\nexport type GetRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n}\n\n/**\n * Options for creating or updating a record in an AT Protocol repository.\n *\n * @see {@link Client.putRecord}\n */\nexport type PutRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Compare-and-swap on the record CID. If specified, must match current record. */\n swapRecord?: string\n /** Whether to validate the record against its lexicon schema. */\n validate?: boolean\n}\n\n/**\n * Options for listing records in an AT Protocol repository collection.\n *\n * @see {@link Client.listRecords}\n */\nexport type ListRecordsOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Maximum number of records to return. */\n limit?: number\n /** Pagination cursor from a previous response. */\n cursor?: string\n /** If true, returns records in reverse chronological order. */\n reverse?: boolean\n}\n\nexport type RecordKeyOptions<\n T extends RecordSchema,\n AlsoOptionalWhenRecordKeyIs extends LexiconRecordKey = never,\n> = T['key'] extends `literal:${string}` | AlsoOptionalWhenRecordKeyIs\n ? { rkey?: InferRecordKey<T> }\n : { rkey: InferRecordKey<T> }\n\n/**\n * Type-safe options for {@link Client.create}, combining record options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type CreateOptions<T extends RecordSchema> = CreateRecordOptions &\n RecordKeyOptions<T, 'tid' | 'any'>\n\n/**\n * Output type for record creation operations.\n * Contains the URI and CID of the newly created record.\n */\nexport type CreateOutput = InferMethodOutputBody<\n typeof com.atproto.repo.createRecord.main,\n Uint8Array\n>\n\n/**\n * Type-safe options for {@link Client.delete}, combining delete options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type DeleteOptions<T extends RecordSchema> = DeleteRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record deletion operations.\n */\nexport type DeleteOutput = InferMethodOutputBody<\n typeof com.atproto.repo.deleteRecord.main,\n Uint8Array\n>\n\n/**\n * Type-safe options for {@link Client.get}, combining get options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type GetOptions<T extends RecordSchema> = GetRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record retrieval operations.\n * Contains the record value validated against the schema type.\n * @typeParam T - The record schema type\n */\nexport type GetOutput<T extends RecordSchema> = Omit<\n InferMethodOutputBody<typeof com.atproto.repo.getRecord.main, Uint8Array>,\n 'value'\n> & { value: Infer<T> }\n\n/**\n * Type-safe options for {@link Client.put}, combining put options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type PutOptions<T extends RecordSchema> = PutRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record put (create/update) operations.\n * Contains the URI and CID of the record.\n */\nexport type PutOutput = InferMethodOutputBody<\n typeof com.atproto.repo.putRecord.main,\n Uint8Array\n>\n\n/**\n * Options for {@link Client.list} operations.\n */\nexport type ListOptions = ListRecordsOptions\n\n/**\n * Output type for record listing operations.\n * Contains validated records and any invalid records that failed schema validation.\n * @typeParam T - The record schema type\n */\nexport type ListOutput<T extends RecordSchema> = InferMethodOutputBody<\n typeof com.atproto.repo.listRecords.main,\n Uint8Array\n> & {\n /** Records that successfully validated against the schema. */\n records: ListRecord<Infer<T>>[]\n // @NOTE Because the schema uses \"type\": \"unknown\" instead of an open union,\n // we have to use LexMap instead of Unknown$TypedObject here, which is\n // unfortunate.\n /** Records that failed schema validation. */\n invalid: LexMap[]\n}\n\n/**\n * A record from a list operation with its value typed to the schema.\n * @typeParam Value - The validated record value type\n */\nexport type ListRecord<Value extends LexMap> =\n com.atproto.repo.listRecords.Record & {\n value: Value\n }\n\n/**\n * The Client class is the primary interface for interacting with AT Protocol\n * services. It provides type-safe methods for XRPC calls, record operations,\n * and blob handling.\n *\n * @example Basic usage\n * ```typescript\n * import { Client } from '@atproto/lex'\n *\n * const client = new Client(agent)\n * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport class Client implements Agent {\n static appLabelers: readonly DidString[] = []\n\n /**\n * Configures the Client (or its sub classes) globally.\n */\n static configure(opts: { appLabelers?: Iterable<DidString> }) {\n if (opts.appLabelers) this.appLabelers = [...opts.appLabelers]\n }\n\n /** The underlying agent used for making requests. */\n public readonly agent: Agent\n\n /** Custom headers included in all requests. */\n public readonly headers: Headers\n\n /** Optional service identifier for routing requests. */\n public readonly service?: Service\n\n /** Set of labeler DIDs specific to this client instance. */\n public readonly labelers: Set<DidString>\n\n constructor(agent: Agent | AgentOptions, options: ClientOptions = {}) {\n this.agent = buildAgent(agent)\n this.service = options.service\n this.labelers = new Set(options.labelers)\n this.headers = new Headers(options.headers)\n }\n\n /**\n * The DID of the authenticated user, or `undefined` if not authenticated.\n */\n get did(): DidString | undefined {\n return this.agent.did\n }\n\n /**\n * The DID of the authenticated user.\n * @throws {LexError} with code 'AuthenticationRequired' if not authenticated\n */\n get assertDid(): DidString {\n this.assertAuthenticated()\n return this.did\n }\n\n /**\n * Asserts that the client is authenticated.\n * Use as a type guard when you need to ensure authentication.\n *\n * @throws {LexError} with code 'AuthenticationRequired' if not authenticated\n *\n * @example\n * ```typescript\n * client.assertAuthenticated()\n * // TypeScript now knows client.did is defined\n * console.log(client.did)\n * ```\n */\n public assertAuthenticated(): asserts this is { did: DidString } {\n if (!this.did) throw new LexError('AuthenticationRequired')\n }\n\n /**\n * Replaces all labelers with the given set.\n * @param labelers - Iterable of labeler DIDs\n */\n public setLabelers(labelers: Iterable<DidString> = []) {\n this.clearLabelers()\n this.addLabelers(labelers)\n }\n\n /**\n * Adds labelers to the current set.\n * @param labelers - Iterable of labeler DIDs to add\n */\n public addLabelers(labelers: Iterable<DidString>) {\n for (const labeler of labelers) this.labelers.add(labeler)\n }\n\n /**\n * Removes all labelers from this client instance.\n */\n public clearLabelers() {\n this.labelers.clear()\n }\n\n /**\n * Low-level fetch handler for making requests.\n * @param path - The request path\n * @param init - Request initialization options\n */\n public fetchHandler(path: string, init: RequestInit): Promise<Response> {\n const headers = buildAtprotoHeaders({\n headers: init.headers,\n service: this.service,\n labelers: [\n ...(this.constructor as typeof Client).appLabelers.map(\n (l) => `${l};redact` as const,\n ),\n ...this.labelers,\n ],\n })\n\n // Incoming headers take precedence\n for (const [key, value] of this.headers) {\n if (!headers.has(key)) headers.set(key, value)\n }\n\n // @NOTE The agent here could be another Client instance.\n return this.agent.fetchHandler(path, { ...init, headers })\n }\n\n /**\n * Makes an XRPC request. Throws on failure.\n *\n * @param ns - The lexicon method definition (e.g., `app.bsky.feed.getTimeline`)\n * @param options - Request options including params and body\n * @returns The successful XRPC response\n * @throws {XrpcFailure} when the request fails or returns an error\n *\n * @example Query with parameters\n * ```typescript\n * const response = await client.xrpc(app.bsky.feed.getTimeline, {\n * params: { limit: 50, cursor: 'abc123' }\n * })\n * console.log(response.body.feed)\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const response = await client.xrpc(com.atproto.repo.createRecord, {\n * body: {\n * repo: client.assertDid,\n * collection: 'app.bsky.feed.post',\n * record: { text: 'Hello!', createdAt: new Date().toISOString() }\n * }\n * })\n * ```\n *\n * @see {@link xrpcSafe} for a non-throwing variant\n */\n async xrpc<const M extends Query | Procedure>(\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n ): Promise<XrpcResponse<M>>\n async xrpc<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M>,\n ): Promise<XrpcResponse<M>>\n async xrpc<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n ): Promise<XrpcResponse<M>> {\n return xrpc(this, ns, options)\n }\n\n /**\n * Makes an XRPC request without throwing on failure.\n * Returns either a successful response or a failure object.\n *\n * @param ns - The lexicon method definition\n * @param options - Request options\n * @returns Either an XrpcResponse on success or XrpcFailure on failure\n *\n * @example\n * ```typescript\n * const result = await client.xrpcSafe(app.bsky.actor.getProfile.main, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Failed:', result.error)\n * }\n * ```\n *\n * @see {@link xrpc} for a throwing variant\n */\n async xrpcSafe<const M extends Query | Procedure>(\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>>\n async xrpcSafe<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>>\n async xrpcSafe<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>> {\n return xrpcSafe(this, ns, options)\n }\n\n /**\n * Creates a new record in an AT Protocol repository.\n *\n * @param record - The record to create, must include an {@link NsidString} `$type`\n * @param rkey - Optional record key; if omitted, server generates a TID\n * @param options - Create options including repo, swapCommit, validate\n * @returns The XRPC response containing the created record's URI and CID\n *\n * @example\n * ```typescript\n * const response = await client.createRecord(\n * { $type: 'app.bsky.feed.post', text: 'Hello!', createdAt: new Date().toISOString() },\n * undefined, // Let server generate rkey\n * { validate: true }\n * )\n * console.log(response.body.uri)\n * ```\n *\n * @see {@link create} for a higher-level typed alternative\n */\n public async createRecord(\n record: TypedLexMap<NsidString>,\n rkey?: string,\n options?: CreateRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.createRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection: record.$type,\n record,\n rkey,\n validate: options?.validate,\n swapCommit: options?.swapCommit,\n },\n })\n }\n\n /**\n * Deletes a record from an AT Protocol repository.\n *\n * @param collection - The collection NSID\n * @param rkey - The record key\n * @param options - Delete options including repo, swapCommit, swapRecord\n *\n * @see {@link delete} for a higher-level typed alternative\n */\n async deleteRecord(\n collection: NsidString,\n rkey: string,\n options?: DeleteRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.deleteRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection,\n rkey,\n swapCommit: options?.swapCommit,\n swapRecord: options?.swapRecord,\n },\n })\n }\n\n /**\n * Retrieves a record from an AT Protocol repository.\n *\n * @param collection - The collection NSID\n * @param rkey - The record key\n * @param options - Get options including repo\n *\n * @see {@link get} for a higher-level typed alternative\n */\n public async getRecord(\n collection: NsidString,\n rkey: string,\n options?: GetRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.getRecord.main, {\n ...options,\n params: {\n repo: options?.repo ?? this.assertDid,\n collection,\n rkey,\n },\n })\n }\n\n /**\n * Creates or updates a record in a repository.\n *\n * @param record - The record to put, must include an {@link NsidString} `$type`\n * @param rkey - The record key\n * @param options - Put options including repo, swapCommit, swapRecord, validate\n *\n * @see {@link put} for a higher-level typed alternative\n */\n async putRecord(\n record: TypedLexMap<NsidString>,\n rkey: string,\n options?: PutRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.putRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection: record.$type,\n rkey,\n record,\n validate: options?.validate,\n swapCommit: options?.swapCommit,\n swapRecord: options?.swapRecord,\n },\n })\n }\n\n /**\n * Lists records in a collection.\n *\n * @param nsid - The collection NSID\n * @param options - List options including repo, limit, cursor, reverse\n *\n * @see {@link list} for a higher-level typed alternative\n */\n async listRecords(nsid: NsidString, options?: ListRecordsOptions) {\n return this.xrpc(com.atproto.repo.listRecords.main, {\n ...options,\n params: {\n repo: options?.repo ?? this.assertDid,\n collection: nsid,\n cursor: options?.cursor,\n limit: options?.limit,\n reverse: options?.reverse,\n },\n })\n }\n\n /**\n * Uploads a blob to an AT Protocol repository.\n *\n * @param body - The blob data (Uint8Array, ReadableStream, Blob, etc.)\n * @param options - Upload options including encoding hint\n * @returns Response containing the blob reference\n *\n * @example\n * ```typescript\n * const imageData = await fetch('image.png').then(r => r.arrayBuffer())\n * const response = await client.uploadBlob(new Uint8Array(imageData), {\n * encoding: 'image/png'\n * })\n * console.log(response.body.blob) // Use this ref in records\n * ```\n */\n async uploadBlob(\n body: BinaryBodyInit,\n options?: CallOptions & { encoding?: `${string}/${string}` },\n ) {\n return this.xrpc(com.atproto.repo.uploadBlob.main, {\n ...options,\n body,\n })\n }\n\n /**\n * Retrieves a blob by DID and CID.\n *\n * @param did - The DID of the repository containing the blob\n * @param cid - The CID of the blob\n * @param options - Call options\n */\n async getBlob(did: DidString, cid: CidString, options?: CallOptions) {\n return this.xrpc(com.atproto.sync.getBlob.main, {\n ...options,\n params: { did, cid },\n })\n }\n\n /**\n * Universal call method for queries, procedures, and custom actions.\n * Automatically determines the call type based on the lexicon definition.\n *\n * @param ns - The lexicon method or action definition\n * @param arg - The input argument (params for queries, body for procedures, input for actions)\n * @param options - Call options\n * @returns The method response body or action output\n * @see {@link xrpc} if you need access to the full response object\n *\n * @example Query\n * ```typescript\n * const profile = await client.call(app.bsky.actor.getProfile.main, {\n * actor: 'alice.bsky.social'\n * })\n * ```\n *\n * @example Procedure\n * ```typescript\n * const result = await client.call(com.atproto.repo.createRecord.main, {\n * repo: did,\n * collection: 'app.bsky.feed.post',\n * record: { text: 'Hello!' }\n * })\n * ```\n */\n public async call<const T extends Query>(\n ns: NonNullable<unknown> extends XrpcRequestParams<T>\n ? Main<T>\n : Restricted<'This query type requires a \"params\" argument'>,\n ): Promise<XrpcResponseBody<T>>\n public async call<const T extends Procedure>(\n ns: undefined extends InferMethodInputBody<T, Uint8Array>\n ? Main<T>\n : Restricted<'This procedure type requires an \"input\" argument'>,\n ): Promise<XrpcResponseBody<T>>\n public async call<const T extends Action>(\n ns: void extends InferActionInput<T>\n ? Main<T>\n : Restricted<'This action type requires an \"input\" argument'>,\n ): Promise<InferActionOutput<T>>\n public async call<const T extends Action | Procedure | Query>(\n ns: Main<T>,\n arg: T extends Action\n ? InferActionInput<T>\n : T extends Procedure\n ? InferMethodInputBody<T, Uint8Array>\n : T extends Query\n ? XrpcRequestParams<T>\n : never,\n options?: CallOptions,\n ): Promise<\n T extends Action\n ? InferActionOutput<T>\n : T extends Procedure\n ? XrpcResponseBody<T>\n : T extends Query\n ? XrpcResponseBody<T>\n : never\n >\n public async call(\n ns: Main<Action> | Main<Procedure> | Main<Query>,\n arg?: LexValue | Params,\n options: CallOptions = {},\n ): Promise<unknown> {\n const method = getMain(ns)\n\n if (typeof method === 'function') {\n return method(this, arg, options)\n }\n\n if (method instanceof Procedure) {\n const result = await this.xrpc(method, { ...options, body: arg as any })\n return result.body\n } else if (method instanceof Query) {\n const result = await this.xrpc(method, { ...options, params: arg as any })\n return result.body\n } else {\n throw new TypeError('Invalid lexicon')\n }\n }\n\n /**\n * Creates a new record with full type safety based on the schema.\n *\n * @param ns - The record schema definition\n * @param input - The record data (without `$type`, which is added automatically)\n * @param options - Create options including rkey (required for some record types)\n * @returns The create output including URI and CID\n *\n * @example Creating a post\n * ```typescript\n * const result = await client.create(app.bsky.feed.post.main, {\n * text: 'Hello, world!',\n * createdAt: new Date().toISOString()\n * })\n * console.log(result.uri)\n * ```\n *\n * @example Creating a record with explicit rkey\n * ```typescript\n * const result = await client.create(app.bsky.actor.profile.main, {\n * displayName: 'Alice'\n * }, { rkey: 'self' })\n * ```\n */\n public async create<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends CreateOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n input: Omit<Infer<T>, '$type'>,\n ): Promise<CreateOutput>\n public async create<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: CreateOptions<T>,\n ): Promise<CreateOutput>\n public async create<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: CreateOptions<T> = {} as CreateOptions<T>,\n ): Promise<CreateOutput> {\n const schema: T = getMain(ns)\n const record = schema.build(input) as TypedLexMap<NsidString>\n const rkey = options.rkey ?? getDefaultRecordKey(schema)\n if (rkey !== undefined) schema.keySchema.assert(rkey)\n const response = await this.createRecord(record, rkey, options)\n return response.body\n }\n\n /**\n * Deletes a record with type-safe options.\n *\n * @param ns - The record schema definition\n * @param options - Delete options (rkey required for non-literal keys)\n * @returns The delete output\n */\n public async delete<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends DeleteOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n ): Promise<DeleteOutput>\n public async delete<const T extends RecordSchema>(\n ns: Main<T>,\n options?: DeleteOptions<T>,\n ): Promise<DeleteOutput>\n public async delete<const T extends RecordSchema>(\n ns: Main<T>,\n options: DeleteOptions<T> = {} as DeleteOptions<T>,\n ): Promise<DeleteOutput> {\n const schema = getMain(ns)\n const rkey = schema.keySchema.parse(\n options.rkey ?? getLiteralRecordKey(schema),\n )\n const response = await this.deleteRecord(schema.$type, rkey, options)\n return response.body\n }\n\n /**\n * Retrieves a record with type-safe validation.\n *\n * @param ns - The record schema definition\n * @param options - Get options (rkey required for non-literal keys)\n * @returns The record data validated against the schema\n *\n * @example\n * ```typescript\n * const profile = await client.get(app.bsky.actor.profile.main)\n * // profile.value is typed as app.bsky.actor.profile.Record\n * console.log(profile.value.displayName)\n * ```\n */\n public async get<const T extends RecordSchema>(\n ns: T['key'] extends `literal:${string}`\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n ): Promise<GetOutput<T>>\n public async get<const T extends RecordSchema>(\n ns: Main<T>,\n options?: GetOptions<T>,\n ): Promise<GetOutput<T>>\n public async get<const T extends RecordSchema>(\n ns: Main<T>,\n options: GetOptions<T> = {} as GetOptions<T>,\n ): Promise<GetOutput<T>> {\n const schema = getMain(ns)\n const rkey = schema.keySchema.parse(\n options.rkey ?? getLiteralRecordKey(schema),\n )\n const response = await this.getRecord(schema.$type, rkey, options)\n const value = schema.validate(response.body.value)\n return { ...response.body, value }\n }\n\n /**\n * Creates or updates a record with full type safety.\n *\n * @param ns - The record schema definition\n * @param input - The record data\n * @param options - Put options (rkey required for non-literal keys)\n * @returns The put output including URI and CID\n */\n public async put<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends PutOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n input: Omit<Infer<T>, '$type'>,\n ): Promise<PutOutput>\n public async put<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: PutOptions<T>,\n ): Promise<PutOutput>\n public async put<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: PutOptions<T> = {} as PutOptions<T>,\n ): Promise<PutOutput> {\n const schema: T = getMain(ns)\n const record = schema.build(input) as TypedLexMap<NsidString>\n const rkey = options.rkey ?? getLiteralRecordKey(schema)\n const response = await this.putRecord(record, rkey, options)\n return response.body\n }\n\n /**\n * Lists records with type-safe validation and separation of valid/invalid records.\n *\n * @param ns - The record schema definition\n * @param options - List options\n * @returns Records split into valid (matching schema) and invalid arrays\n *\n * @example\n * ```typescript\n * const result = await client.list(app.bsky.feed.post.main, { limit: 100 })\n * console.log(`Found ${result.records.length} valid posts`)\n * console.log(`Found ${result.invalid.length} invalid records`)\n * ```\n */\n async list<const T extends RecordSchema>(\n ns: Main<T>,\n options?: ListOptions,\n ): Promise<ListOutput<T>> {\n const schema = getMain(ns)\n const { body } = await this.listRecords(schema.$type, options)\n\n const records: ListRecord<Infer<T>>[] = []\n const invalid: LexMap[] = []\n\n for (const record of body.records) {\n const parsed = schema.safeValidate(record.value)\n if (parsed.success) {\n records.push({ ...record, value: parsed.value })\n } else {\n invalid.push(record.value)\n }\n }\n\n return { ...body, records, invalid }\n }\n}\n\nfunction getDefaultRecordKey<const T extends RecordSchema>(\n schema: T,\n): undefined | InferRecordKey<T> {\n // Let the server generate the TID\n if (schema.key === 'tid') return undefined\n if (schema.key === 'any') return undefined\n\n return getLiteralRecordKey(schema)\n}\n\nfunction getLiteralRecordKey<const T extends RecordSchema>(\n schema: T,\n): InferRecordKey<T> {\n if (schema.key.startsWith('literal:')) {\n return schema.key.slice(8) as InferRecordKey<T>\n }\n\n throw new TypeError(\n `An \"rkey\" must be provided for record key type \"${schema.key}\" (${schema.$type})`,\n )\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,gDAA2E;AAC3E,oDAiB4B;AAC5B,yCAA4D;AAE5D,kDAAyC;AAGzC,uCAA+C;AAC/C,uCAA0E;AA8P1E;;;;;;;;;;;;;;;GAeG;AACH,MAAa,MAAM;IACjB,MAAM,CAAC,WAAW,GAAyB,EAAE,CAAA;IAE7C;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,IAA2C;QAC1D,IAAI,IAAI,CAAC,WAAW;YAAE,IAAI,CAAC,WAAW,GAAG,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,CAAA;IAChE,CAAC;IAED,qDAAqD;IACrC,KAAK,CAAO;IAE5B,+CAA+C;IAC/B,OAAO,CAAS;IAEhC,wDAAwD;IACxC,OAAO,CAAU;IAEjC,4DAA4D;IAC5C,QAAQ,CAAgB;IAExC,YAAY,KAA2B,EAAE,UAAyB,EAAE;QAClE,IAAI,CAAC,KAAK,GAAG,IAAA,qBAAU,EAAC,KAAK,CAAC,CAAA;QAC9B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAA;QAC9B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AAC,KAAK,EAAE,OAAO,CAAC,CAAA;QAE9D,MAAM,OAAO,GAA2B,EAAE,CAAA;QAC1C,MAAM,OAAO,GAAa,EAAE,CAAA;QAE5B,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YAClC,MAAM,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAChD,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBACnB,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAA;YAClD,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YAC5B,CAAC;QACH,CAAC;QAED,OAAO,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA;IACtC,CAAC;;AA/nBH,wBAgoBC;AAED,SAAS,mBAAmB,CAC1B,MAAS;IAET,kCAAkC;IAClC,IAAI,MAAM,CAAC,GAAG,KAAK,KAAK;QAAE,OAAO,SAAS,CAAA;IAC1C,IAAI,MAAM,CAAC,GAAG,KAAK,KAAK;QAAE,OAAO,SAAS,CAAA;IAE1C,OAAO,mBAAmB,CAAC,MAAM,CAAC,CAAA;AACpC,CAAC;AAED,SAAS,mBAAmB,CAC1B,MAAS;IAET,IAAI,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;QACtC,OAAO,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAsB,CAAA;IACjD,CAAC;IAED,MAAM,IAAI,SAAS,CACjB,mDAAmD,MAAM,CAAC,GAAG,MAAM,MAAM,CAAC,KAAK,GAAG,CACnF,CAAA;AACH,CAAC","sourcesContent":["import { LexError, LexMap, LexValue, TypedLexMap } from '@atproto/lex-data'\nimport {\n AtIdentifierString,\n CidString,\n DidString,\n Infer,\n InferMethodInputBody,\n InferMethodOutputBody,\n InferRecordKey,\n LexiconRecordKey,\n Main,\n NsidString,\n Params,\n Procedure,\n Query,\n RecordSchema,\n Restricted,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent, AgentOptions, buildAgent } from './agent.js'\nimport { XrpcFailure } from './errors.js'\nimport { com } from './lexicons/index.js'\nimport { XrpcResponse, XrpcResponseBody } from './response.js'\nimport { BinaryBodyInit, CallOptions, Service } from './types.js'\nimport { buildAtprotoHeaders } from './util.js'\nimport { XrpcOptions, XrpcRequestParams, xrpc, xrpcSafe } from './xrpc.js'\n\nexport type {\n AtIdentifierString,\n CidString,\n DidString,\n Infer,\n InferMethodInputBody,\n InferMethodOutputBody,\n InferRecordKey,\n LexMap,\n LexValue,\n LexiconRecordKey,\n Main,\n NsidString,\n Params,\n Procedure,\n Query,\n RecordSchema,\n Restricted,\n TypedLexMap,\n}\n\n/**\n * Configuration options for creating a {@link Client}.\n *\n * @example\n * ```typescript\n * const options: ClientOptions = {\n * labelers: ['did:plc:labeler1'],\n * service: 'did:web:api.bsky.app#bsky_appview',\n * headers: { 'X-Custom-Header': 'value' }\n * }\n * ```\n */\nexport type ClientOptions = {\n /** Labeler DIDs to include in requests for content moderation. */\n labelers?: Iterable<DidString>\n /** Custom headers to include in all requests made by this client. */\n headers?: HeadersInit\n /** Service proxy identifier for routing requests through a specific service. */\n service?: Service\n}\n\n/**\n * A composable action that can be invoked via {@link Client.call}.\n *\n * Actions provide a way to define custom operations that integrate with the\n * Client's call interface, enabling type-safe, reusable business logic.\n *\n * @typeParam I - The input type for the action\n * @typeParam O - The output type for the action\n *\n * @example\n * ```typescript\n * const myAction: Action<{ userId: string }, { profile: Profile }> = async (client, input, options) => {\n * const response = await client.xrpc(someMethod, { params: { actor: input.userId }, ...options })\n * return { profile: response.body }\n * }\n * ```\n */\nexport type Action<I = any, O = any> = (\n client: Client,\n input: I,\n options: CallOptions,\n) => O | Promise<O>\n\n/**\n * Extracts the input type from an {@link Action}.\n * @typeParam A - The Action type to extract from\n */\nexport type InferActionInput<A extends Action> =\n A extends Action<infer I, any> ? I : never\n\n/**\n * Extracts the output type from an {@link Action}.\n * @typeParam A - The Action type to extract from\n */\nexport type InferActionOutput<A extends Action> =\n A extends Action<any, infer O> ? O : never\n\n/**\n * Options for creating a record in an AT Protocol repository.\n *\n * @see {@link Client.createRecord}\n */\nexport type CreateRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Whether to validate the record against its lexicon schema. */\n validate?: boolean\n}\n\n/**\n * Options for deleting a record from an AT Protocol repository.\n *\n * @see {@link Client.deleteRecord}\n */\nexport type DeleteRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Compare-and-swap on the record CID. If specified, must match current record. */\n swapRecord?: string\n}\n\n/**\n * Options for retrieving a record from an AT Protocol repository.\n *\n * @see {@link Client.getRecord}\n */\nexport type GetRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n}\n\n/**\n * Options for creating or updating a record in an AT Protocol repository.\n *\n * @see {@link Client.putRecord}\n */\nexport type PutRecordOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Compare-and-swap on the repo commit. If specified, must match current commit. */\n swapCommit?: string\n /** Compare-and-swap on the record CID. If specified, must match current record. */\n swapRecord?: string\n /** Whether to validate the record against its lexicon schema. */\n validate?: boolean\n}\n\n/**\n * Options for listing records in an AT Protocol repository collection.\n *\n * @see {@link Client.listRecords}\n */\nexport type ListRecordsOptions = CallOptions & {\n /** Repository identifier (DID or handle). Defaults to authenticated user's DID. */\n repo?: AtIdentifierString\n /** Maximum number of records to return. */\n limit?: number\n /** Pagination cursor from a previous response. */\n cursor?: string\n /** If true, returns records in reverse chronological order. */\n reverse?: boolean\n}\n\nexport type RecordKeyOptions<\n T extends RecordSchema,\n AlsoOptionalWhenRecordKeyIs extends LexiconRecordKey = never,\n> = T['key'] extends `literal:${string}` | AlsoOptionalWhenRecordKeyIs\n ? { rkey?: InferRecordKey<T> }\n : { rkey: InferRecordKey<T> }\n\n/**\n * Type-safe options for {@link Client.create}, combining record options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type CreateOptions<T extends RecordSchema> = CreateRecordOptions &\n RecordKeyOptions<T, 'tid' | 'any'>\n\n/**\n * Output type for record creation operations.\n * Contains the URI and CID of the newly created record.\n */\nexport type CreateOutput = InferMethodOutputBody<\n typeof com.atproto.repo.createRecord.main,\n Uint8Array\n>\n\n/**\n * Type-safe options for {@link Client.delete}, combining delete options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type DeleteOptions<T extends RecordSchema> = DeleteRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record deletion operations.\n */\nexport type DeleteOutput = InferMethodOutputBody<\n typeof com.atproto.repo.deleteRecord.main,\n Uint8Array\n>\n\n/**\n * Type-safe options for {@link Client.get}, combining get options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type GetOptions<T extends RecordSchema> = GetRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record retrieval operations.\n * Contains the record value validated against the schema type.\n * @typeParam T - The record schema type\n */\nexport type GetOutput<T extends RecordSchema> = Omit<\n InferMethodOutputBody<typeof com.atproto.repo.getRecord.main, Uint8Array>,\n 'value'\n> & { value: Infer<T> }\n\n/**\n * Type-safe options for {@link Client.put}, combining put options with key requirements.\n * @typeParam T - The record schema type\n */\nexport type PutOptions<T extends RecordSchema> = PutRecordOptions &\n RecordKeyOptions<T>\n\n/**\n * Output type for record put (create/update) operations.\n * Contains the URI and CID of the record.\n */\nexport type PutOutput = InferMethodOutputBody<\n typeof com.atproto.repo.putRecord.main,\n Uint8Array\n>\n\n/**\n * Options for {@link Client.list} operations.\n */\nexport type ListOptions = ListRecordsOptions\n\n/**\n * Output type for record listing operations.\n * Contains validated records and any invalid records that failed schema validation.\n * @typeParam T - The record schema type\n */\nexport type ListOutput<T extends RecordSchema> = InferMethodOutputBody<\n typeof com.atproto.repo.listRecords.main,\n Uint8Array\n> & {\n /** Records that successfully validated against the schema. */\n records: ListRecord<Infer<T>>[]\n // @NOTE Because the schema uses \"type\": \"unknown\" instead of an open union,\n // we have to use LexMap instead of Unknown$TypedObject here, which is\n // unfortunate.\n /** Records that failed schema validation. */\n invalid: LexMap[]\n}\n\n/**\n * A record from a list operation with its value typed to the schema.\n * @typeParam Value - The validated record value type\n */\nexport type ListRecord<Value extends LexMap> =\n com.atproto.repo.listRecords.Record & {\n value: Value\n }\n\n/**\n * The Client class is the primary interface for interacting with AT Protocol\n * services. It provides type-safe methods for XRPC calls, record operations,\n * and blob handling.\n *\n * @example // Basic usage\n * ```typescript\n * import { Client } from '@atproto/lex'\n *\n * const client = new Client(oauthSession)\n *\n * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport class Client implements Agent {\n static appLabelers: readonly DidString[] = []\n\n /**\n * Configures the Client (or its sub classes) globally.\n */\n static configure(opts: { appLabelers?: Iterable<DidString> }) {\n if (opts.appLabelers) this.appLabelers = [...opts.appLabelers]\n }\n\n /** The underlying agent used for making requests. */\n public readonly agent: Agent\n\n /** Custom headers included in all requests. */\n public readonly headers: Headers\n\n /** Optional service identifier for routing requests. */\n public readonly service?: Service\n\n /** Set of labeler DIDs specific to this client instance. */\n public readonly labelers: Set<DidString>\n\n constructor(agent: Agent | AgentOptions, options: ClientOptions = {}) {\n this.agent = buildAgent(agent)\n this.service = options.service\n this.labelers = new Set(options.labelers)\n this.headers = new Headers(options.headers)\n }\n\n /**\n * The DID of the authenticated user, or `undefined` if not authenticated.\n */\n get did(): DidString | undefined {\n return this.agent.did\n }\n\n /**\n * The DID of the authenticated user.\n * @throws {LexError} with code 'AuthenticationRequired' if not authenticated\n */\n get assertDid(): DidString {\n this.assertAuthenticated()\n return this.did\n }\n\n /**\n * Asserts that the client is authenticated.\n * Use as a type guard when you need to ensure authentication.\n *\n * @throws {LexError} with code 'AuthenticationRequired' if not authenticated\n *\n * @example\n * ```typescript\n * client.assertAuthenticated()\n * // TypeScript now knows client.did is defined\n * console.log(client.did)\n * ```\n */\n public assertAuthenticated(): asserts this is { did: DidString } {\n if (!this.did) throw new LexError('AuthenticationRequired')\n }\n\n /**\n * Replaces all labelers with the given set.\n * @param labelers - Iterable of labeler DIDs\n */\n public setLabelers(labelers: Iterable<DidString> = []) {\n this.clearLabelers()\n this.addLabelers(labelers)\n }\n\n /**\n * Adds labelers to the current set.\n * @param labelers - Iterable of labeler DIDs to add\n */\n public addLabelers(labelers: Iterable<DidString>) {\n for (const labeler of labelers) this.labelers.add(labeler)\n }\n\n /**\n * Removes all labelers from this client instance.\n */\n public clearLabelers() {\n this.labelers.clear()\n }\n\n /**\n * {@link Agent}'s {@link Agent.fetchHandler} implementation, which adds\n * labelers and service proxying headers. This method allow a {@link Client}\n * instance to be used directly as an {@link Agent} for another\n * {@link Client}, enabling composition of headers (labelers, proxying, etc.).\n *\n * @param path - The request path\n * @param init - Request initialization options\n */\n public fetchHandler(\n path: `/${string}`,\n init: RequestInit,\n ): Promise<Response> {\n const headers = buildAtprotoHeaders({\n headers: init.headers,\n service: this.service,\n labelers: [\n ...(this.constructor as typeof Client).appLabelers.map(\n (l) => `${l};redact` as const,\n ),\n ...this.labelers,\n ],\n })\n\n // Incoming headers take precedence\n for (const [key, value] of this.headers) {\n if (!headers.has(key)) headers.set(key, value)\n }\n\n // @NOTE The agent here could be another Client instance.\n return this.agent.fetchHandler(path, { ...init, headers })\n }\n\n /**\n * Makes an XRPC request. Throws on failure.\n *\n * @param ns - The lexicon method definition (e.g., `app.bsky.feed.getTimeline`)\n * @param options - Request options including params and body\n * @returns The successful XRPC response\n * @throws {XrpcFailure} when the request fails or returns an error\n *\n * @example Query with parameters\n * ```typescript\n * const response = await client.xrpc(app.bsky.feed.getTimeline, {\n * params: { limit: 50, cursor: 'abc123' }\n * })\n * console.log(response.body.feed)\n * ```\n *\n * @example Procedure with body\n * ```typescript\n * const response = await client.xrpc(com.atproto.repo.createRecord, {\n * body: {\n * repo: client.assertDid,\n * collection: 'app.bsky.feed.post',\n * record: { text: 'Hello!', createdAt: new Date().toISOString() }\n * }\n * })\n * ```\n *\n * @see {@link xrpcSafe} for a non-throwing variant\n */\n async xrpc<const M extends Query | Procedure>(\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n ): Promise<XrpcResponse<M>>\n async xrpc<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M>,\n ): Promise<XrpcResponse<M>>\n async xrpc<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n ): Promise<XrpcResponse<M>> {\n return xrpc(this, ns, options)\n }\n\n /**\n * Makes an XRPC request without throwing on failure.\n * Returns either a successful response or a failure object.\n *\n * @param ns - The lexicon method definition\n * @param options - Request options\n * @returns Either an XrpcResponse on success or XrpcFailure on failure\n *\n * @example\n * ```typescript\n * const result = await client.xrpcSafe(app.bsky.actor.getProfile.main, {\n * params: { actor: 'alice.bsky.social' }\n * })\n *\n * if (result.success) {\n * console.log(result.body.displayName)\n * } else {\n * console.error('Failed:', result.error)\n * }\n * ```\n *\n * @see {@link xrpc} for a throwing variant\n */\n async xrpcSafe<const M extends Query | Procedure>(\n ns: NonNullable<unknown> extends XrpcOptions<M>\n ? Main<M>\n : Restricted<'This XRPC method requires an \"options\" argument'>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>>\n async xrpcSafe<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>>\n async xrpcSafe<const M extends Query | Procedure>(\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n ): Promise<XrpcResponse<M> | XrpcFailure<M>> {\n return xrpcSafe(this, ns, options)\n }\n\n /**\n * Creates a new record in an AT Protocol repository.\n *\n * @param record - The record to create, must include an {@link NsidString} `$type`\n * @param rkey - Optional record key; if omitted, server generates a TID\n * @param options - Create options including repo, swapCommit, validate\n * @returns The XRPC response containing the created record's URI and CID\n *\n * @example\n * ```typescript\n * const response = await client.createRecord(\n * { $type: 'app.bsky.feed.post', text: 'Hello!', createdAt: new Date().toISOString() },\n * undefined, // Let server generate rkey\n * { validate: true }\n * )\n * console.log(response.body.uri)\n * ```\n *\n * @see {@link create} for a higher-level typed alternative\n */\n public async createRecord(\n record: TypedLexMap<NsidString>,\n rkey?: string,\n options?: CreateRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.createRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection: record.$type,\n record,\n rkey,\n validate: options?.validate,\n swapCommit: options?.swapCommit,\n },\n })\n }\n\n /**\n * Deletes a record from an AT Protocol repository.\n *\n * @param collection - The collection NSID\n * @param rkey - The record key\n * @param options - Delete options including repo, swapCommit, swapRecord\n *\n * @see {@link delete} for a higher-level typed alternative\n */\n async deleteRecord(\n collection: NsidString,\n rkey: string,\n options?: DeleteRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.deleteRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection,\n rkey,\n swapCommit: options?.swapCommit,\n swapRecord: options?.swapRecord,\n },\n })\n }\n\n /**\n * Retrieves a record from an AT Protocol repository.\n *\n * @param collection - The collection NSID\n * @param rkey - The record key\n * @param options - Get options including repo\n *\n * @see {@link get} for a higher-level typed alternative\n */\n public async getRecord(\n collection: NsidString,\n rkey: string,\n options?: GetRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.getRecord.main, {\n ...options,\n params: {\n repo: options?.repo ?? this.assertDid,\n collection,\n rkey,\n },\n })\n }\n\n /**\n * Creates or updates a record in a repository.\n *\n * @param record - The record to put, must include an {@link NsidString} `$type`\n * @param rkey - The record key\n * @param options - Put options including repo, swapCommit, swapRecord, validate\n *\n * @see {@link put} for a higher-level typed alternative\n */\n async putRecord(\n record: TypedLexMap<NsidString>,\n rkey: string,\n options?: PutRecordOptions,\n ) {\n return this.xrpc(com.atproto.repo.putRecord.main, {\n ...options,\n body: {\n repo: options?.repo ?? this.assertDid,\n collection: record.$type,\n rkey,\n record,\n validate: options?.validate,\n swapCommit: options?.swapCommit,\n swapRecord: options?.swapRecord,\n },\n })\n }\n\n /**\n * Lists records in a collection.\n *\n * @param nsid - The collection NSID\n * @param options - List options including repo, limit, cursor, reverse\n *\n * @see {@link list} for a higher-level typed alternative\n */\n async listRecords(nsid: NsidString, options?: ListRecordsOptions) {\n return this.xrpc(com.atproto.repo.listRecords.main, {\n ...options,\n params: {\n repo: options?.repo ?? this.assertDid,\n collection: nsid,\n cursor: options?.cursor,\n limit: options?.limit,\n reverse: options?.reverse,\n },\n })\n }\n\n /**\n * Uploads a blob to an AT Protocol repository.\n *\n * @param body - The blob data (Uint8Array, ReadableStream, Blob, etc.)\n * @param options - Upload options including encoding hint\n * @returns Response containing the blob reference\n *\n * @example\n * ```typescript\n * const imageData = await fetch('image.png').then(r => r.arrayBuffer())\n * const response = await client.uploadBlob(new Uint8Array(imageData), {\n * encoding: 'image/png'\n * })\n * console.log(response.body.blob) // Use this ref in records\n * ```\n */\n async uploadBlob(\n body: BinaryBodyInit,\n options?: CallOptions & { encoding?: `${string}/${string}` },\n ) {\n return this.xrpc(com.atproto.repo.uploadBlob.main, {\n ...options,\n body,\n })\n }\n\n /**\n * Retrieves a blob by DID and CID.\n *\n * @param did - The DID of the repository containing the blob\n * @param cid - The CID of the blob\n * @param options - Call options\n */\n async getBlob(did: DidString, cid: CidString, options?: CallOptions) {\n return this.xrpc(com.atproto.sync.getBlob.main, {\n ...options,\n params: { did, cid },\n })\n }\n\n /**\n * Universal call method for queries, procedures, and custom actions.\n * Automatically determines the call type based on the lexicon definition.\n *\n * @param ns - The lexicon method or action definition\n * @param arg - The input argument (params for queries, body for procedures, input for actions)\n * @param options - Call options\n * @returns The method response body or action output\n * @see {@link xrpc} if you need access to the full response object\n *\n * @example Query\n * ```typescript\n * const profile = await client.call(app.bsky.actor.getProfile.main, {\n * actor: 'alice.bsky.social'\n * })\n * ```\n *\n * @example Procedure\n * ```typescript\n * const result = await client.call(com.atproto.repo.createRecord.main, {\n * repo: did,\n * collection: 'app.bsky.feed.post',\n * record: { text: 'Hello!' }\n * })\n * ```\n */\n public async call<const T extends Query>(\n ns: NonNullable<unknown> extends XrpcRequestParams<T>\n ? Main<T>\n : Restricted<'This query type requires a \"params\" argument'>,\n ): Promise<XrpcResponseBody<T>>\n public async call<const T extends Procedure>(\n ns: undefined extends InferMethodInputBody<T, Uint8Array>\n ? Main<T>\n : Restricted<'This procedure type requires an \"input\" argument'>,\n ): Promise<XrpcResponseBody<T>>\n public async call<const T extends Action>(\n ns: void extends InferActionInput<T>\n ? Main<T>\n : Restricted<'This action type requires an \"input\" argument'>,\n ): Promise<InferActionOutput<T>>\n public async call<const T extends Action | Procedure | Query>(\n ns: Main<T>,\n arg: T extends Action\n ? InferActionInput<T>\n : T extends Procedure\n ? InferMethodInputBody<T, Uint8Array>\n : T extends Query\n ? XrpcRequestParams<T>\n : never,\n options?: CallOptions,\n ): Promise<\n T extends Action\n ? InferActionOutput<T>\n : T extends Procedure\n ? XrpcResponseBody<T>\n : T extends Query\n ? XrpcResponseBody<T>\n : never\n >\n public async call(\n ns: Main<Action> | Main<Procedure> | Main<Query>,\n arg?: LexValue | Params,\n options: CallOptions = {},\n ): Promise<unknown> {\n const method = getMain(ns)\n\n if (typeof method === 'function') {\n return method(this, arg, options)\n }\n\n if (method instanceof Procedure) {\n const result = await this.xrpc(method, { ...options, body: arg as any })\n return result.body\n } else if (method instanceof Query) {\n const result = await this.xrpc(method, { ...options, params: arg as any })\n return result.body\n } else {\n throw new TypeError('Invalid lexicon')\n }\n }\n\n /**\n * Creates a new record with full type safety based on the schema.\n *\n * @param ns - The record schema definition\n * @param input - The record data (without `$type`, which is added automatically)\n * @param options - Create options including rkey (required for some record types)\n * @returns The create output including URI and CID\n *\n * @example Creating a post\n * ```typescript\n * const result = await client.create(app.bsky.feed.post.main, {\n * text: 'Hello, world!',\n * createdAt: new Date().toISOString()\n * })\n * console.log(result.uri)\n * ```\n *\n * @example Creating a record with explicit rkey\n * ```typescript\n * const result = await client.create(app.bsky.actor.profile.main, {\n * displayName: 'Alice'\n * }, { rkey: 'self' })\n * ```\n */\n public async create<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends CreateOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n input: Omit<Infer<T>, '$type'>,\n ): Promise<CreateOutput>\n public async create<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: CreateOptions<T>,\n ): Promise<CreateOutput>\n public async create<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: CreateOptions<T> = {} as CreateOptions<T>,\n ): Promise<CreateOutput> {\n const schema: T = getMain(ns)\n const record = schema.build(input) as TypedLexMap<NsidString>\n const rkey = options.rkey ?? getDefaultRecordKey(schema)\n if (rkey !== undefined) schema.keySchema.assert(rkey)\n const response = await this.createRecord(record, rkey, options)\n return response.body\n }\n\n /**\n * Deletes a record with type-safe options.\n *\n * @param ns - The record schema definition\n * @param options - Delete options (rkey required for non-literal keys)\n * @returns The delete output\n */\n public async delete<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends DeleteOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n ): Promise<DeleteOutput>\n public async delete<const T extends RecordSchema>(\n ns: Main<T>,\n options?: DeleteOptions<T>,\n ): Promise<DeleteOutput>\n public async delete<const T extends RecordSchema>(\n ns: Main<T>,\n options: DeleteOptions<T> = {} as DeleteOptions<T>,\n ): Promise<DeleteOutput> {\n const schema = getMain(ns)\n const rkey = schema.keySchema.parse(\n options.rkey ?? getLiteralRecordKey(schema),\n )\n const response = await this.deleteRecord(schema.$type, rkey, options)\n return response.body\n }\n\n /**\n * Retrieves a record with type-safe validation.\n *\n * @param ns - The record schema definition\n * @param options - Get options (rkey required for non-literal keys)\n * @returns The record data validated against the schema\n *\n * @example\n * ```typescript\n * const profile = await client.get(app.bsky.actor.profile.main)\n * // profile.value is typed as app.bsky.actor.profile.Record\n * console.log(profile.value.displayName)\n * ```\n */\n public async get<const T extends RecordSchema>(\n ns: T['key'] extends `literal:${string}`\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n ): Promise<GetOutput<T>>\n public async get<const T extends RecordSchema>(\n ns: Main<T>,\n options?: GetOptions<T>,\n ): Promise<GetOutput<T>>\n public async get<const T extends RecordSchema>(\n ns: Main<T>,\n options: GetOptions<T> = {} as GetOptions<T>,\n ): Promise<GetOutput<T>> {\n const schema = getMain(ns)\n const rkey = schema.keySchema.parse(\n options.rkey ?? getLiteralRecordKey(schema),\n )\n const response = await this.getRecord(schema.$type, rkey, options)\n const value = schema.validate(response.body.value)\n return { ...response.body, value }\n }\n\n /**\n * Creates or updates a record with full type safety.\n *\n * @param ns - The record schema definition\n * @param input - The record data\n * @param options - Put options (rkey required for non-literal keys)\n * @returns The put output including URI and CID\n */\n public async put<const T extends RecordSchema>(\n ns: NonNullable<unknown> extends PutOptions<T>\n ? Main<T>\n : Restricted<'This record type requires an \"options\" argument'>,\n input: Omit<Infer<T>, '$type'>,\n ): Promise<PutOutput>\n public async put<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: PutOptions<T>,\n ): Promise<PutOutput>\n public async put<const T extends RecordSchema>(\n ns: Main<T>,\n input: Omit<Infer<T>, '$type'>,\n options: PutOptions<T> = {} as PutOptions<T>,\n ): Promise<PutOutput> {\n const schema: T = getMain(ns)\n const record = schema.build(input) as TypedLexMap<NsidString>\n const rkey = options.rkey ?? getLiteralRecordKey(schema)\n const response = await this.putRecord(record, rkey, options)\n return response.body\n }\n\n /**\n * Lists records with type-safe validation and separation of valid/invalid records.\n *\n * @param ns - The record schema definition\n * @param options - List options\n * @returns Records split into valid (matching schema) and invalid arrays\n *\n * @example\n * ```typescript\n * const result = await client.list(app.bsky.feed.post.main, { limit: 100 })\n * console.log(`Found ${result.records.length} valid posts`)\n * console.log(`Found ${result.invalid.length} invalid records`)\n * ```\n */\n async list<const T extends RecordSchema>(\n ns: Main<T>,\n options?: ListOptions,\n ): Promise<ListOutput<T>> {\n const schema = getMain(ns)\n const { body } = await this.listRecords(schema.$type, options)\n\n const records: ListRecord<Infer<T>>[] = []\n const invalid: LexMap[] = []\n\n for (const record of body.records) {\n const parsed = schema.safeValidate(record.value)\n if (parsed.success) {\n records.push({ ...record, value: parsed.value })\n } else {\n invalid.push(record.value)\n }\n }\n\n return { ...body, records, invalid }\n }\n}\n\nfunction getDefaultRecordKey<const T extends RecordSchema>(\n schema: T,\n): undefined | InferRecordKey<T> {\n // Let the server generate the TID\n if (schema.key === 'tid') return undefined\n if (schema.key === 'any') return undefined\n\n return getLiteralRecordKey(schema)\n}\n\nfunction getLiteralRecordKey<const T extends RecordSchema>(\n schema: T,\n): InferRecordKey<T> {\n if (schema.key.startsWith('literal:')) {\n return schema.key.slice(8) as InferRecordKey<T>\n }\n\n throw new TypeError(\n `An \"rkey\" must be provided for record key type \"${schema.key}\" (${schema.$type})`,\n )\n}\n"]}
package/dist/xrpc.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { InferInput, InferPayload, Main, Params, Procedure, Query, Restricted, Subscription } from '@atproto/lex-schema';
2
- import { Agent } from './agent.js';
2
+ import { Agent, AgentOptions } from './agent.js';
3
3
  import { XrpcFailure } from './errors.js';
4
4
  import { XrpcResponse } from './response.js';
5
5
  import { BinaryBodyInit, CallOptions } from './types.js';
@@ -54,8 +54,7 @@ export type XrpcOptions<M extends Procedure | Query = Procedure | Query> = CallO
54
54
  /**
55
55
  * Makes an XRPC request and throws on failure.
56
56
  *
57
- * This is the low-level function for making XRPC calls. For most use cases,
58
- * prefer using {@link Client.xrpc} which provides a more ergonomic API.
57
+ * This is the low-level function for making XRPC calls.
59
58
  *
60
59
  * @param agent - The {@link Agent} to use for making the request
61
60
  * @param ns - The lexicon method definition
@@ -65,13 +64,20 @@ export type XrpcOptions<M extends Procedure | Query = Procedure | Query> = CallO
65
64
  *
66
65
  * @example
67
66
  * ```typescript
67
+ * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {
68
+ * params: { handle: "atproto.com" }
69
+ * })
70
+ * ```
71
+ *
72
+ * @example
73
+ * ```typescript
68
74
  * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {
69
75
  * params: { limit: 50 }
70
76
  * })
71
77
  * ```
72
78
  */
73
- export declare function xrpc<const M extends Query | Procedure>(agent: Agent, ns: NonNullable<unknown> extends XrpcOptions<M> ? Main<M> : Restricted<'This XRPC method requires an "options" argument'>): Promise<XrpcResponse<M>>;
74
- export declare function xrpc<const M extends Query | Procedure>(agent: Agent, ns: Main<M>, options: XrpcOptions<M>): Promise<XrpcResponse<M>>;
79
+ export declare function xrpc<const M extends Query | Procedure>(agentOpts: Agent | AgentOptions, ns: NonNullable<unknown> extends XrpcOptions<M> ? Main<M> : Restricted<'This XRPC method requires an "options" argument'>): Promise<XrpcResponse<M>>;
80
+ export declare function xrpc<const M extends Query | Procedure>(agentOpts: Agent | AgentOptions, ns: Main<M>, options: XrpcOptions<M>): Promise<XrpcResponse<M>>;
75
81
  /**
76
82
  * Union type representing either a successful response or a failure.
77
83
  *
@@ -96,7 +102,7 @@ export type XrpcResult<M extends Procedure | Query> = XrpcResponse<M> | XrpcFail
96
102
  *
97
103
  * @example
98
104
  * ```typescript
99
- * const result = await xrpcSafe(agent, app.bsky.actor.getProfile.main, {
105
+ * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {
100
106
  * params: { actor: 'alice.bsky.social' }
101
107
  * })
102
108
  *
@@ -107,7 +113,7 @@ export type XrpcResult<M extends Procedure | Query> = XrpcResponse<M> | XrpcFail
107
113
  * }
108
114
  * ```
109
115
  */
110
- export declare function xrpcSafe<const M extends Query | Procedure>(agent: Agent, ns: NonNullable<unknown> extends XrpcOptions<M> ? Main<M> : Restricted<'This XRPC method requires an "options" argument'>): Promise<XrpcResult<M>>;
111
- export declare function xrpcSafe<const M extends Query | Procedure>(agent: Agent, ns: Main<M>, options: XrpcOptions<M>): Promise<XrpcResult<M>>;
116
+ export declare function xrpcSafe<const M extends Query | Procedure>(agentOpts: Agent | AgentOptions, ns: NonNullable<unknown> extends XrpcOptions<M> ? Main<M> : Restricted<'This XRPC method requires an "options" argument'>): Promise<XrpcResult<M>>;
117
+ export declare function xrpcSafe<const M extends Query | Procedure>(agentOpts: Agent | AgentOptions, ns: Main<M>, options: XrpcOptions<M>): Promise<XrpcResult<M>>;
112
118
  export {};
113
119
  //# sourceMappingURL=xrpc.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"xrpc.d.ts","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,YAAY,EACZ,IAAI,EACJ,MAAM,EAEN,SAAS,EACT,KAAK,EACL,UAAU,EACV,YAAY,EAEb,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAA;AAClC,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,EAA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
@@ -5,20 +5,22 @@ exports.xrpcSafe = xrpcSafe;
5
5
  const lex_data_1 = require("@atproto/lex-data");
6
6
  const lex_json_1 = require("@atproto/lex-json");
7
7
  const lex_schema_1 = require("@atproto/lex-schema");
8
+ const agent_js_1 = require("./agent.js");
8
9
  const errors_js_1 = require("./errors.js");
9
10
  const response_js_1 = require("./response.js");
10
11
  const util_js_1 = require("./util.js");
11
- async function xrpc(agent, ns, options = {}) {
12
- const response = await xrpcSafe(agent, ns, options);
12
+ async function xrpc(agentOpts, ns, options = {}) {
13
+ const response = await xrpcSafe(agentOpts, ns, options);
13
14
  if (response.success)
14
15
  return response;
15
16
  else
16
17
  throw response;
17
18
  }
18
- async function xrpcSafe(agent, ns, options = {}) {
19
+ async function xrpcSafe(agentOpts, ns, options = {}) {
19
20
  options.signal?.throwIfAborted();
20
21
  const method = (0, lex_schema_1.getMain)(ns);
21
22
  try {
23
+ const agent = (0, agent_js_1.buildAgent)(agentOpts);
22
24
  const url = xrpcRequestUrl(method, options);
23
25
  const request = xrpcRequestInit(method, options);
24
26
  const response = await agent.fetchHandler(url, request);
package/dist/xrpc.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"xrpc.js","sourceRoot":"","sources":["../src/xrpc.ts"],"names":[],"mappings":";;AA0GA,oBAQC;AAmDD,4BAeC;AApLD,gDAAwE;AACxE,gDAAgD;AAChD,oDAW4B;AAE5B,2CAAwD;AACxD,+CAA4C;AAE5C,uCAKkB;AAmFX,KAAK,UAAU,IAAI,CACxB,KAAY,EACZ,EAAW,EACX,UAA0B,EAAoB;IAE9C,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAI,KAAK,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;IACtD,IAAI,QAAQ,CAAC,OAAO;QAAE,OAAO,QAAQ,CAAA;;QAChC,MAAM,QAAQ,CAAA;AACrB,CAAC;AAmDM,KAAK,UAAU,QAAQ,CAC5B,KAAY,EACZ,EAAW,EACX,UAA0B,EAAoB;I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E,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 Params,\n Payload,\n Procedure,\n Query,\n Restricted,\n Subscription,\n getMain,\n} from '@atproto/lex-schema'\nimport { Agent } 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. For most use cases,\n * prefer using {@link Client.xrpc} which provides a more ergonomic API.\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(agent, app.bsky.feed.getTimeline.main, {\n * params: { limit: 50 }\n * })\n * ```\n */\nexport async function xrpc<const M extends Query | Procedure>(\n agent: Agent,\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 agent: Agent,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResponse<M>>\nexport async function xrpc<const M extends Query | Procedure>(\n agent: Agent,\n ns: Main<M>,\n options: XrpcOptions<M> = {} as XrpcOptions<M>,\n): Promise<XrpcResponse<M>> {\n const response = await xrpcSafe<M>(agent, 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(agent, app.bsky.actor.getProfile.main, {\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 agent: Agent,\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 agent: Agent,\n ns: Main<M>,\n options: XrpcOptions<M>,\n): Promise<XrpcResult<M>>\nexport async function xrpcSafe<const M extends Query | Procedure>(\n agent: Agent,\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 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) {\n const path = `/xrpc/${method.nsid}`\n\n const queryString = method.parameters\n ?.toURLSearchParams(options.params ?? {})\n .toString()\n\n return queryString ? `${path}?${queryString}` : 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,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;IAC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-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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/lex-client",
3
- "version": "0.0.13",
3
+ "version": "0.0.14",
4
4
  "license": "MIT",
5
5
  "description": "HTTP client for interacting with Lexicon based APIs",
6
6
  "keywords": [
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "vitest": "^4.0.16",
46
- "@atproto/lex-cbor": "^0.0.12",
46
+ "@atproto/lex-cbor": "^0.0.13",
47
47
  "@atproto/lex-builder": "^0.0.16"
48
48
  },
49
49
  "scripts": {
package/src/agent.ts CHANGED
@@ -5,7 +5,7 @@ import { DidString } from '@atproto/lex-schema'
5
5
  *
6
6
  * The handler is responsible for adding the origin (protocol, hostname, and
7
7
  * port) to the provided path, typically based on authentication or service
8
- * configuration. The handler are also responsible for adding any necessary
8
+ * configuration. The handler can also be responsible for adding any necessary
9
9
  * headers, such as authorization tokens.
10
10
  *
11
11
  * @param path - The URL path (pathname + query parameters) without the origin
@@ -18,16 +18,23 @@ export type FetchHandler = (
18
18
  * origin. The origin (protocol, hostname, and port) must be added by this
19
19
  * {@link FetchHandler}, typically based on authentication or other factors.
20
20
  */
21
- path: string,
21
+ path: `/${string}`,
22
22
  init: RequestInit,
23
23
  ) => Promise<Response>
24
24
 
25
25
  /**
26
- * Core interface for making XRPC requests.
26
+ * Core interface for making XRPC requests towards a specific service.
27
27
  *
28
- * An Agent encapsulates an identity and request handling for AT Protocol
29
- * operations. It can represent an authenticated user session or an
30
- * unauthenticated service client.
28
+ * An {@link Agent} encapsulates an identity and request handling for AT
29
+ * Protocol operations. Agents will typically handle authentication, service URL
30
+ * resolution, and other request configuration, allowing client code to make
31
+ * requests without needing to manage these details directly. The key component
32
+ * of an Agent is the {@link FetchHandler}, which is responsible for
33
+ * constructing the full request URL and adding any necessary headers or
34
+ * authentication tokens. The Agent's `did` property represents the
35
+ * authenticated user's DID, if available, and can be used for operations that
36
+ * require knowledge of the user's identity (such as creating AT Protocol
37
+ * records).
31
38
  *
32
39
  * @see {@link buildAgent} for creating (simple) Agent instances.
33
40
  *
@@ -35,7 +42,10 @@ export type FetchHandler = (
35
42
  * ```typescript
36
43
  * const agent: Agent = {
37
44
  * did: 'did:plc:example123',
38
- * fetchHandler: (path, init) => fetch(new URL(path, 'https://bsky.social'), init)
45
+ * fetchHandler: async (path, init) => {
46
+ * const url = new URL(path, 'https://bsky.social')
47
+ * return fetch(url, init)
48
+ * }
39
49
  * }
40
50
  * ```
41
51
  */
@@ -46,6 +56,18 @@ export interface Agent {
46
56
  fetchHandler: FetchHandler
47
57
  }
48
58
 
59
+ export function isAgent(value: unknown): value is Agent {
60
+ return (
61
+ typeof value === 'object' &&
62
+ value !== null &&
63
+ 'fetchHandler' in value &&
64
+ typeof value.fetchHandler === 'function' &&
65
+ (!('did' in value) ||
66
+ value.did === undefined ||
67
+ typeof value.did === 'string')
68
+ )
69
+ }
70
+
49
71
  export type AgentConfig = {
50
72
  /**
51
73
  * The identifier (DID) of the user represented by this agent.
@@ -84,20 +106,20 @@ export type AgentOptions = AgentConfig | string | URL
84
106
  /**
85
107
  * Creates an {@link Agent} from various input types.
86
108
  *
87
- * This factory function accepts an existing Agent (returned as-is), a service URL,
88
- * or a full configuration object. It handles the common case of creating an
89
- * unauthenticated agent from just a service URL.
109
+ * This factory function accepts an existing Agent (returned as-is), a service
110
+ * URL, or a full configuration object. It handles the common case of creating
111
+ * an unauthenticated agent from just a service URL.
90
112
  *
91
113
  * @param options - Agent instance, configuration object, or service URL
92
114
  * @returns A configured Agent ready for making requests
93
115
  * @throws {TypeError} If fetch() is not available in the environment
94
116
  *
95
- * @example From URL string
117
+ * @example // From URL string
96
118
  * ```typescript
97
119
  * const agent = buildAgent('https://public.api.bsky.app')
98
120
  * ```
99
121
  *
100
- * @example From configuration
122
+ * @example // From configuration
101
123
  * ```typescript
102
124
  * const agent = buildAgent({
103
125
  * did: 'did:plc:example',
@@ -105,17 +127,12 @@ export type AgentOptions = AgentConfig | string | URL
105
127
  * headers: { 'Authorization': 'Bearer ...' }
106
128
  * })
107
129
  * ```
108
- *
109
- * @example Pass-through existing agent
110
- * ```typescript
111
- * const existing: Agent = { ... }
112
- * const agent = buildAgent(existing) // Returns existing unchanged
113
- * ```
114
130
  */
131
+ export function buildAgent<O extends Agent | AgentOptions>(
132
+ options: O,
133
+ ): O extends Agent ? O : Agent
115
134
  export function buildAgent(options: Agent | AgentOptions): Agent {
116
- if (typeof options === 'object' && 'fetchHandler' in options) {
117
- return options
118
- }
135
+ if (isAgent(options)) return options
119
136
 
120
137
  const config: Agent | AgentConfig =
121
138
  typeof options === 'string' || options instanceof URL
package/src/client.ts CHANGED
@@ -282,11 +282,12 @@ export type ListRecord<Value extends LexMap> =
282
282
  * services. It provides type-safe methods for XRPC calls, record operations,
283
283
  * and blob handling.
284
284
  *
285
- * @example Basic usage
285
+ * @example // Basic usage
286
286
  * ```typescript
287
287
  * import { Client } from '@atproto/lex'
288
288
  *
289
- * const client = new Client(agent)
289
+ * const client = new Client(oauthSession)
290
+ *
290
291
  * const response = await client.xrpc(app.bsky.feed.getTimeline.main, {
291
292
  * params: { limit: 50 }
292
293
  * })
@@ -379,11 +380,18 @@ export class Client implements Agent {
379
380
  }
380
381
 
381
382
  /**
382
- * Low-level fetch handler for making requests.
383
+ * {@link Agent}'s {@link Agent.fetchHandler} implementation, which adds
384
+ * labelers and service proxying headers. This method allow a {@link Client}
385
+ * instance to be used directly as an {@link Agent} for another
386
+ * {@link Client}, enabling composition of headers (labelers, proxying, etc.).
387
+ *
383
388
  * @param path - The request path
384
389
  * @param init - Request initialization options
385
390
  */
386
- public fetchHandler(path: string, init: RequestInit): Promise<Response> {
391
+ public fetchHandler(
392
+ path: `/${string}`,
393
+ init: RequestInit,
394
+ ): Promise<Response> {
387
395
  const headers = buildAtprotoHeaders({
388
396
  headers: init.headers,
389
397
  service: this.service,
package/src/xrpc.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  InferInput,
5
5
  InferPayload,
6
6
  Main,
7
+ NsidString,
7
8
  Params,
8
9
  Payload,
9
10
  Procedure,
@@ -12,7 +13,7 @@ import {
12
13
  Subscription,
13
14
  getMain,
14
15
  } from '@atproto/lex-schema'
15
- import { Agent } from './agent.js'
16
+ import { Agent, AgentOptions, buildAgent } from './agent.js'
16
17
  import { XrpcFailure, asXrpcFailure } from './errors.js'
17
18
  import { XrpcResponse } from './response.js'
18
19
  import { BinaryBodyInit, CallOptions } from './types.js'
@@ -77,8 +78,7 @@ export type XrpcOptions<M extends Procedure | Query = Procedure | Query> =
77
78
  /**
78
79
  * Makes an XRPC request and throws on failure.
79
80
  *
80
- * This is the low-level function for making XRPC calls. For most use cases,
81
- * prefer using {@link Client.xrpc} which provides a more ergonomic API.
81
+ * This is the low-level function for making XRPC calls.
82
82
  *
83
83
  * @param agent - The {@link Agent} to use for making the request
84
84
  * @param ns - The lexicon method definition
@@ -88,28 +88,35 @@ export type XrpcOptions<M extends Procedure | Query = Procedure | Query> =
88
88
  *
89
89
  * @example
90
90
  * ```typescript
91
+ * const response = await xrpc('https://bsky.network', com.atproto.identity.resolveHandle, {
92
+ * params: { handle: "atproto.com" }
93
+ * })
94
+ * ```
95
+ *
96
+ * @example
97
+ * ```typescript
91
98
  * const response = await xrpc(agent, app.bsky.feed.getTimeline.main, {
92
99
  * params: { limit: 50 }
93
100
  * })
94
101
  * ```
95
102
  */
96
103
  export async function xrpc<const M extends Query | Procedure>(
97
- agent: Agent,
104
+ agentOpts: Agent | AgentOptions,
98
105
  ns: NonNullable<unknown> extends XrpcOptions<M>
99
106
  ? Main<M>
100
107
  : Restricted<'This XRPC method requires an "options" argument'>,
101
108
  ): Promise<XrpcResponse<M>>
102
109
  export async function xrpc<const M extends Query | Procedure>(
103
- agent: Agent,
110
+ agentOpts: Agent | AgentOptions,
104
111
  ns: Main<M>,
105
112
  options: XrpcOptions<M>,
106
113
  ): Promise<XrpcResponse<M>>
107
114
  export async function xrpc<const M extends Query | Procedure>(
108
- agent: Agent,
115
+ agentOpts: Agent | AgentOptions,
109
116
  ns: Main<M>,
110
117
  options: XrpcOptions<M> = {} as XrpcOptions<M>,
111
118
  ): Promise<XrpcResponse<M>> {
112
- const response = await xrpcSafe<M>(agent, ns, options)
119
+ const response = await xrpcSafe<M>(agentOpts, ns, options)
113
120
  if (response.success) return response
114
121
  else throw response
115
122
  }
@@ -141,7 +148,7 @@ export type XrpcResult<M extends Procedure | Query> =
141
148
  *
142
149
  * @example
143
150
  * ```typescript
144
- * const result = await xrpcSafe(agent, app.bsky.actor.getProfile.main, {
151
+ * const result = await xrpcSafe('https://example.com', app.bsky.actor.getProfile, {
145
152
  * params: { actor: 'alice.bsky.social' }
146
153
  * })
147
154
  *
@@ -153,24 +160,25 @@ export type XrpcResult<M extends Procedure | Query> =
153
160
  * ```
154
161
  */
155
162
  export async function xrpcSafe<const M extends Query | Procedure>(
156
- agent: Agent,
163
+ agentOpts: Agent | AgentOptions,
157
164
  ns: NonNullable<unknown> extends XrpcOptions<M>
158
165
  ? Main<M>
159
166
  : Restricted<'This XRPC method requires an "options" argument'>,
160
167
  ): Promise<XrpcResult<M>>
161
168
  export async function xrpcSafe<const M extends Query | Procedure>(
162
- agent: Agent,
169
+ agentOpts: Agent | AgentOptions,
163
170
  ns: Main<M>,
164
171
  options: XrpcOptions<M>,
165
172
  ): Promise<XrpcResult<M>>
166
173
  export async function xrpcSafe<const M extends Query | Procedure>(
167
- agent: Agent,
174
+ agentOpts: Agent | AgentOptions,
168
175
  ns: Main<M>,
169
176
  options: XrpcOptions<M> = {} as XrpcOptions<M>,
170
177
  ): Promise<XrpcResult<M>> {
171
178
  options.signal?.throwIfAborted()
172
179
  const method: M = getMain(ns)
173
180
  try {
181
+ const agent = buildAgent(agentOpts)
174
182
  const url = xrpcRequestUrl(method, options)
175
183
  const request = xrpcRequestInit(method, options)
176
184
  const response = await agent.fetchHandler(url, request)
@@ -183,14 +191,14 @@ export async function xrpcSafe<const M extends Query | Procedure>(
183
191
  function xrpcRequestUrl<M extends Procedure | Query | Subscription>(
184
192
  method: M,
185
193
  options: CallOptions & { params?: Params },
186
- ) {
187
- const path = `/xrpc/${method.nsid}`
194
+ ): `/xrpc/${NsidString}${'' | `?${string}`}` {
195
+ const path = `/xrpc/${method.nsid}` as const
188
196
 
189
197
  const queryString = method.parameters
190
198
  ?.toURLSearchParams(options.params ?? {})
191
199
  .toString()
192
200
 
193
- return queryString ? `${path}?${queryString}` : path
201
+ return queryString ? (`${path}?${queryString}` as const) : path
194
202
  }
195
203
 
196
204
  function xrpcRequestInit<T extends Procedure | Query>(