@atproto/xrpc 0.5.0 → 0.5.1-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,9 +9,9 @@ TypeScript client library for talking to [atproto](https://atproto.com) services
9
9
 
10
10
  ```typescript
11
11
  import { LexiconDoc } from '@atproto/lexicon'
12
- import xrpc from '@atproto/xrpc'
12
+ import { XrpcClient } from '@atproto/xrpc'
13
13
 
14
- const pingLexicon: LexiconDoc = {
14
+ const pingLexicon = {
15
15
  lexicon: 1,
16
16
  id: 'io.example.ping',
17
17
  defs: {
@@ -32,44 +32,69 @@ const pingLexicon: LexiconDoc = {
32
32
  },
33
33
  },
34
34
  },
35
- }
36
- xrpc.addLexicon(pingLexicon)
35
+ } satisfies LexiconDoc
36
+
37
+ const xrpc = new XrpcClient('https://ping.example.com', [
38
+ // Any number of lexicon here
39
+ pingLexicon,
40
+ ])
37
41
 
38
- const res1 = await xrpc.call('https://example.com', 'io.example.ping', {
42
+ const res1 = await xrpc.call('io.example.ping', {
39
43
  message: 'hello world',
40
44
  })
41
45
  res1.encoding // => 'application/json'
42
46
  res1.body // => {message: 'hello world'}
43
- const res2 = await xrpc
44
- .service('https://example.com')
45
- .call('io.example.ping', { message: 'hello world' })
46
- res2.encoding // => 'application/json'
47
- res2.body // => {message: 'hello world'}
47
+ ```
48
48
 
49
- const writeJsonLexicon: LexiconDoc = {
50
- lexicon: 1,
51
- id: 'io.example.writeJsonFile',
52
- defs: {
53
- main: {
54
- type: 'procedure',
55
- description: 'Write a JSON file',
56
- parameters: {
57
- type: 'params',
58
- properties: { fileName: { type: 'string' } },
59
- },
60
- input: {
61
- encoding: 'application/json',
62
- },
63
- },
49
+ ### With a custom fetch handler
50
+
51
+ ```typescript
52
+ import { XrpcClient } from '@atproto/xrpc'
53
+
54
+ const session = {
55
+ serviceUrl: 'https://ping.example.com',
56
+ token: '<my-token>',
57
+ async refreshToken() {
58
+ const { token } = await fetch('https://auth.example.com/refresh', {
59
+ method: 'POST',
60
+ headers: { Authorization: `Bearer ${this.token}` },
61
+ }).then((res) => res.json())
62
+
63
+ this.token = token
64
+
65
+ return token
64
66
  },
65
67
  }
66
- xrpc.addLexicon(writeJsonLexicon)
67
68
 
68
- const res3 = await xrpc.service('https://example.com').call(
69
- 'io.example.writeJsonFile',
70
- { fileName: 'foo.json' }, // query parameters
71
- { hello: 'world', thisIs: 'the file to write' }, // input body
72
- )
69
+ const sessionBasedFetch: FetchHandler = async (
70
+ url: string,
71
+ init: RequestInit,
72
+ ) => {
73
+ const headers = new Headers(init.headers)
74
+
75
+ headers.set('Authorization', `Bearer ${session.token}`)
76
+
77
+ const response = await fetch(new URL(url, session.serviceUrl), {
78
+ ...init,
79
+ headers,
80
+ })
81
+
82
+ if (response.status === 401) {
83
+ // Refresh token, then try again.
84
+ const newToken = await session.refreshToken()
85
+ headers.set('Authorization', `Bearer ${newToken}`)
86
+ return fetch(new URL(url, session.serviceUrl), { ...init, headers })
87
+ }
88
+
89
+ return response
90
+ }
91
+
92
+ const xrpc = new XrpcClient(sessionBasedFetch, [
93
+ // Any number of lexicon here
94
+ pingLexicon,
95
+ ])
96
+
97
+ //
73
98
  ```
74
99
 
75
100
  ## License
package/dist/client.d.ts CHANGED
@@ -1,22 +1,26 @@
1
1
  import { LexiconDoc, Lexicons } from '@atproto/lexicon';
2
- import { FetchHandler, FetchHandlerResponse, Headers, CallOptions, QueryParams, XRPCResponse } from './types';
2
+ import { CallOptions, QueryParams } from './types';
3
+ import { XrpcClient } from './xrpc-client';
4
+ /** @deprecated Use {@link XrpcClient} instead */
3
5
  export declare class Client {
4
- fetch: FetchHandler;
6
+ /** @deprecated */
7
+ get fetch(): never;
8
+ /** @deprecated */
9
+ set fetch(_: never);
5
10
  lex: Lexicons;
6
- call(serviceUri: string | URL, methodNsid: string, params?: QueryParams, data?: unknown, opts?: CallOptions): Promise<XRPCResponse>;
11
+ call(serviceUri: string | URL, methodNsid: string, params?: QueryParams, data?: BodyInit | null, opts?: CallOptions): Promise<import("./types").XRPCResponse>;
7
12
  service(serviceUri: string | URL): ServiceClient;
8
13
  addLexicon(doc: LexiconDoc): void;
9
14
  addLexicons(docs: LexiconDoc[]): void;
10
15
  removeLexicon(uri: string): void;
11
16
  }
12
- export declare class ServiceClient {
17
+ /** @deprecated Use {@link XrpcClient} instead */
18
+ export declare class ServiceClient extends XrpcClient {
13
19
  baseClient: Client;
14
20
  uri: URL;
15
21
  headers: Record<string, string>;
16
22
  constructor(baseClient: Client, serviceUri: string | URL);
17
23
  setHeader(key: string, value: string): void;
18
24
  unsetHeader(key: string): void;
19
- call(methodNsid: string, params?: QueryParams, data?: unknown, opts?: CallOptions): Promise<XRPCResponse>;
20
25
  }
21
- export declare function defaultFetchHandler(httpUri: string, httpMethod: string, httpHeaders: Headers, httpReqBody: unknown): Promise<FetchHandlerResponse>;
22
26
  //# sourceMappingURL=client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAmB,MAAM,kBAAkB,CAAA;AAUxE,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,OAAO,EACP,WAAW,EACX,WAAW,EAIX,YAAY,EAGb,MAAM,SAAS,CAAA;AAEhB,qBAAa,MAAM;IACjB,KAAK,EAAE,YAAY,CAAsB;IACzC,GAAG,WAAiB;IAKd,IAAI,CACR,UAAU,EAAE,MAAM,GAAG,GAAG,EACxB,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,WAAW,EACpB,IAAI,CAAC,EAAE,OAAO,EACd,IAAI,CAAC,EAAE,WAAW;IAKpB,OAAO,CAAC,UAAU,EAAE,MAAM,GAAG,GAAG;IAOhC,UAAU,CAAC,GAAG,EAAE,UAAU;IAI1B,WAAW,CAAC,IAAI,EAAE,UAAU,EAAE;IAM9B,aAAa,CAAC,GAAG,EAAE,M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AAE,MAAM,GAAG,GAAG;IAOhC,UAAU,CAAC,GAAG,EAAE,UAAU;IAI1B,WAAW,CAAC,IAAI,EAAE,UAAU,EAAE;IAM9B,aAAa,CAAC,GAAG,EAAE,MAAM;CAG1B;AAED,iDAAiD;AACjD,qBAAa,aAAc,SAAQ,UAAU;IAKlC,UAAU,EAAE,MAAM;IAJ3B,GAAG,EAAE,GAAG,CAAA;IACR,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAK;gBAG3B,UAAU,EAAE,MAAM,EACzB,UAAU,EAAE,MAAM,GAAG,GAAG;IAS1B,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3C,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;CAG/B"}
package/dist/client.js CHANGED
@@ -1,17 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.defaultFetchHandler = exports.ServiceClient = exports.Client = void 0;
3
+ exports.ServiceClient = exports.Client = void 0;
4
4
  const lexicon_1 = require("@atproto/lexicon");
5
+ const xrpc_client_1 = require("./xrpc-client");
5
6
  const util_1 = require("./util");
6
- const types_1 = require("./types");
7
+ /** @deprecated Use {@link XrpcClient} instead */
7
8
  class Client {
8
9
  constructor() {
9
- Object.defineProperty(this, "fetch", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: defaultFetchHandler
14
- });
15
10
  Object.defineProperty(this, "lex", {
16
11
  enumerable: true,
17
12
  configurable: true,
@@ -19,6 +14,14 @@ class Client {
19
14
  value: new lexicon_1.Lexicons()
20
15
  });
21
16
  }
17
+ /** @deprecated */
18
+ get fetch() {
19
+ throw new Error('Client.fetch is no longer supported. Use an XrpcClient instead.');
20
+ }
21
+ /** @deprecated */
22
+ set fetch(_) {
23
+ throw new Error('Client.fetch is no longer supported. Use an XrpcClient instead.');
24
+ }
22
25
  // method calls
23
26
  //
24
27
  async call(serviceUri, methodNsid, params, data, opts) {
@@ -42,13 +45,18 @@ class Client {
42
45
  }
43
46
  }
44
47
  exports.Client = Client;
45
- class ServiceClient {
48
+ /** @deprecated Use {@link XrpcClient} instead */
49
+ class ServiceClient extends xrpc_client_1.XrpcClient {
46
50
  constructor(baseClient, serviceUri) {
51
+ super(async (input, init) => {
52
+ const headers = (0, util_1.combineHeaders)(init.headers, Object.entries(this.headers));
53
+ return fetch(new URL(input, this.uri), { ...init, headers });
54
+ }, baseClient.lex);
47
55
  Object.defineProperty(this, "baseClient", {
48
56
  enumerable: true,
49
57
  configurable: true,
50
58
  writable: true,
51
- value: void 0
59
+ value: baseClient
52
60
  });
53
61
  Object.defineProperty(this, "uri", {
54
62
  enumerable: true,
@@ -62,7 +70,6 @@ class ServiceClient {
62
70
  writable: true,
63
71
  value: {}
64
72
  });
65
- this.baseClient = baseClient;
66
73
  this.uri = typeof serviceUri === 'string' ? new URL(serviceUri) : serviceUri;
67
74
  }
68
75
  setHeader(key, value) {
@@ -71,72 +78,6 @@ class ServiceClient {
71
78
  unsetHeader(key) {
72
79
  delete this.headers[key];
73
80
  }
74
- async call(methodNsid, params, data, opts) {
75
- const def = this.baseClient.lex.getDefOrThrow(methodNsid);
76
- if (!def || (def.type !== 'query' && def.type !== 'procedure')) {
77
- throw new Error(`Invalid lexicon: ${methodNsid}. Must be a query or procedure.`);
78
- }
79
- const httpMethod = (0, util_1.getMethodSchemaHTTPMethod)(def);
80
- const httpUri = (0, util_1.constructMethodCallUri)(methodNsid, def, this.uri, params);
81
- const httpHeaders = (0, util_1.constructMethodCallHeaders)(def, data, {
82
- headers: {
83
- ...this.headers,
84
- ...opts?.headers,
85
- },
86
- encoding: opts?.encoding,
87
- });
88
- const res = await this.baseClient.fetch(httpUri, httpMethod, httpHeaders, data);
89
- const resCode = (0, util_1.httpResponseCodeToEnum)(res.status);
90
- if (resCode === types_1.ResponseType.Success) {
91
- try {
92
- this.baseClient.lex.assertValidXrpcOutput(methodNsid, res.body);
93
- }
94
- catch (e) {
95
- if (e instanceof lexicon_1.ValidationError) {
96
- throw new types_1.XRPCInvalidResponseError(methodNsid, e, res.body);
97
- }
98
- else {
99
- throw e;
100
- }
101
- }
102
- return new types_1.XRPCResponse(res.body, res.headers);
103
- }
104
- else {
105
- if (res.body && isErrorResponseBody(res.body)) {
106
- throw new types_1.XRPCError(resCode, res.body.error, res.body.message, res.headers);
107
- }
108
- else {
109
- throw new types_1.XRPCError(resCode);
110
- }
111
- }
112
- }
113
81
  }
114
82
  exports.ServiceClient = ServiceClient;
115
- async function defaultFetchHandler(httpUri, httpMethod, httpHeaders, httpReqBody) {
116
- try {
117
- // The duplex field is now required for streaming bodies, but not yet reflected
118
- // anywhere in docs or types. See whatwg/fetch#1438, nodejs/node#46221.
119
- const headers = (0, util_1.normalizeHeaders)(httpHeaders);
120
- const reqInit = {
121
- method: httpMethod,
122
- headers,
123
- body: (0, util_1.encodeMethodCallBody)(headers, httpReqBody),
124
- duplex: 'half',
125
- };
126
- const res = await fetch(httpUri, reqInit);
127
- const resBody = await res.arrayBuffer();
128
- return {
129
- status: res.status,
130
- headers: Object.fromEntries(res.headers.entries()),
131
- body: (0, util_1.httpResponseBodyParse)(res.headers.get('content-type'), resBody),
132
- };
133
- }
134
- catch (e) {
135
- throw new types_1.XRPCError(types_1.ResponseType.Unknown, String(e));
136
- }
137
- }
138
- exports.defaultFetchHandler = defaultFetchHandler;
139
- function isErrorResponseBody(v) {
140
- return types_1.errorResponseBody.safeParse(v).success;
141
- }
142
83
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,8CAAwE;AACxE,iCAQe;AACf,mCAYgB;AAEhB,MAAa,MAAM;IAAnB;QACE;;;;mBAAsB,mBAAmB;WAAA;QACzC;;;;mBAAM,IAAI,kBAAQ,EAAE;WAAA;IAmCtB,CAAC;IAjCC,eAAe;IACf,EAAE;IAEF,KAAK,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AAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;QACtB,CAAC;IACH,CAAC;IAED,aAAa,CAAC,GAAW;QACvB,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACtB,CAAC;CACF;AAlDD,wBAkDC;AAED,iDAAiD;AACjD,MAAa,aAAc,SAAQ,wBAAU;IAI3C,YACS,UAAkB,EACzB,UAAwB;QAExB,KAAK,CAAC,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;YAC1B,MAAM,OAAO,GAAG,IAAA,qBAAc,EAAC,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAA;YAC1E,OAAO,KAAK,CAAC,IAAI,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAA;QAC9D,CAAC,EAAE,UAAU,CAAC,GAAG,CAAC,CAAA;QANlB;;;;mBAAO,UAAU;WAAQ;QAJ3B;;;;;WAAQ;QACR;;;;mBAAkC,EAAE;WAAA;QAUlC,IAAI,CAAC,GAAG,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAA;IAC9E,CAAC;IAED,SAAS,CAAC,GAAW,EAAE,KAAa;QAClC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAA;IAC3B,CAAC;IAED,WAAW,CAAC,GAAW;QACrB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC1B,CAAC;CACF;AAtBD,sCAsBC"}
@@ -0,0 +1,33 @@
1
+ import { Gettable } from './types';
2
+ export type FetchHandler = (this: void,
3
+ /**
4
+ * The URL (pathname + query parameters) to make the request to, without the
5
+ * origin. The origin (protocol, hostname, and port) must be added by this
6
+ * {@link FetchHandler}, typically based on authentication or other factors.
7
+ */
8
+ url: string, init: RequestInit) => Promise<Response>;
9
+ export type FetchHandlerOptions = BuildFetchHandlerOptions | string | URL;
10
+ export type BuildFetchHandlerOptions = {
11
+ /**
12
+ * The service URL to make requests to. This can be a string, URL, or a
13
+ * function that returns a string or URL. This is useful for dynamic URLs,
14
+ * such as a service URL that changes based on authentication.
15
+ */
16
+ service: Gettable<string | URL>;
17
+ /**
18
+ * Headers to be added to every request. If a function is provided, it will be
19
+ * called on each request to get the headers. This is useful for dynamic
20
+ * headers, such as authentication tokens that may expire.
21
+ */
22
+ headers?: {
23
+ [_ in string]?: Gettable<null | string>;
24
+ };
25
+ /**
26
+ * Bring your own fetch implementation. Typically useful for testing, logging,
27
+ * mocking, or adding retries, session management, signatures, proof of
28
+ * possession (DPoP), etc. Defaults to the global `fetch` function.
29
+ */
30
+ fetch?: typeof globalThis.fetch;
31
+ };
32
+ export declare function buildFetchHandler(options: FetchHandler | FetchHandlerOptions): FetchHandler;
33
+ //# sourceMappingURL=fetch-handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-handler.d.ts","sourceRoot":"","sources":["../src/fetch-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAA;AAGlC,MAAM,MAAM,YAAY,GAAG,CACzB,IAAI,EAAE,IAAI;AACV;;;;GAIG;AACH,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,WAAW,KACd,OAAO,CAAC,QAAQ,CAAC,CAAA;AAEtB,MAAM,MAAM,mBAAmB,GAAG,wBAAwB,GAAG,MAAM,GAAG,GAAG,CAAA;AAEzE,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;OAIG;IACH,OAAO,EAAE,QAAQ,CAAC,MAAM,GAAG,GAAG,CAAC,CAAA;IAE/B;;;;OAIG;IACH,OAAO,CAAC,EAAE;SACP,CAAC,IAAI,MAAM,CAAC,CAAC,EAAE,QAAQ,CAAC,IAAI,GAAG,MAAM,CAAC;KACxC,CAAA;IAED;;;;OAIG;IACH,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAA;CAChC,CAAA;AAED,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,YAAY,GAAG,mBAAmB,GAC1C,YAAY,CA6Bd"}
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildFetchHandler = void 0;
4
+ const util_1 = require("./util");
5
+ function buildFetchHandler(options) {
6
+ // Already a fetch handler (allowed for convenience)
7
+ if (typeof options === 'function')
8
+ return options;
9
+ const { service, headers: defaultHeaders = undefined, fetch = globalThis.fetch, } = typeof options === 'string' || options instanceof URL
10
+ ? { service: options }
11
+ : options;
12
+ if (typeof fetch !== 'function') {
13
+ throw new TypeError('XrpcDispatcher requires fetch() to be available in your environment.');
14
+ }
15
+ const defaultHeadersEntries = defaultHeaders != null ? Object.entries(defaultHeaders) : undefined;
16
+ return async function (url, init) {
17
+ const base = typeof service === 'function' ? service() : service;
18
+ const fullUrl = new URL(url, base);
19
+ const headers = (0, util_1.combineHeaders)(init.headers, defaultHeadersEntries);
20
+ return fetch(fullUrl, { ...init, headers });
21
+ };
22
+ }
23
+ exports.buildFetchHandler = buildFetchHandler;
24
+ //# sourceMappingURL=fetch-handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-handler.js","sourceRoot":"","sources":["../src/fetch-handler.ts"],"names":[],"mappings":";;;AACA,iCAAuC;AAwCvC,SAAgB,iBAAiB,CAC/B,OAA2C;IAE3C,oDAAoD;IACpD,IAAI,OAAO,OAAO,KAAK,UAAU;QAAE,OAAO,OAAO,CAAA;IAEjD,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,KAAK,GAAG,UAAU,CAAC,KAAK,GACzB,GAAG,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,YAAY,GAAG;QACvD,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE;QACtB,CAAC,CAAC,OAAO,CAAA;IAEX,IAAI,OAAO,KAAK,KAAK,UAAU,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CACjB,sEAAsE,CACvE,CAAA;IACH,CAAC;IAED,MAAM,qBAAqB,GACzB,cAAc,IAAI,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;IAErE,OAAO,KAAK,WAAW,GAAG,EAAE,IAAI;QAC9B,MAAM,IAAI,GAAG,OAAO,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAA;QAChE,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAA;QAElC,MAAM,OAAO,GAAG,IAAA,qBAAc,EAAC,IAAI,CAAC,OAAO,EAAE,qBAAqB,CAAC,CAAA;QAEnE,OAAO,KAAK,CAAC,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAA;IAC7C,CAAC,CAAA;AACH,CAAC;AA/BD,8CA+BC"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,10 @@
1
- export * from './types';
2
1
  export * from './client';
2
+ export * from './fetch-handler';
3
+ export * from './types';
4
+ export * from './util';
5
+ export * from './xrpc-client';
3
6
  import { Client } from './client';
7
+ /** @deprecated create a local {@link XrpcClient} instance instead */
4
8
  declare const defaultInst: Client;
5
9
  export default defaultInst;
6
10
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAA;AACvB,cAAc,UAAU,CAAA;AAExB,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,QAAA,MAAM,WAAW,QAAe,CAAA;AAChC,eAAe,WAAW,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAA;AACxB,cAAc,iBAAiB,CAAA;AAC/B,cAAc,SAAS,CAAA;AACvB,cAAc,QAAQ,CAAA;AACtB,cAAc,eAAe,CAAA;AAE7B,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,qEAAqE;AACrE,QAAA,MAAM,WAAW,QAAe,CAAA;AAChC,eAAe,WAAW,CAAA"}
package/dist/index.js CHANGED
@@ -14,9 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
18
17
  __exportStar(require("./client"), exports);
18
+ __exportStar(require("./fetch-handler"), exports);
19
+ __exportStar(require("./types"), exports);
20
+ __exportStar(require("./util"), exports);
21
+ __exportStar(require("./xrpc-client"), exports);
19
22
  const client_1 = require("./client");
23
+ /** @deprecated create a local {@link XrpcClient} instance instead */
20
24
  const defaultInst = new client_1.Client();
21
25
  exports.default = defaultInst;
22
26
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAuB;AACvB,2CAAwB;AAExB,qCAAiC;AACjC,MAAM,WAAW,GAAG,IAAI,eAAM,EAAE,CAAA;AAChC,kBAAe,WAAW,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAwB;AACxB,kDAA+B;AAC/B,0CAAuB;AACvB,yCAAsB;AACtB,gDAA6B;AAE7B,qCAAiC;AACjC,qEAAqE;AACrE,MAAM,WAAW,GAAG,IAAI,eAAM,EAAE,CAAA;AAChC,kBAAe,WAAW,CAAA"}
package/dist/types.d.ts CHANGED
@@ -1,17 +1,15 @@
1
1
  import { z } from 'zod';
2
2
  import { ValidationError } from '@atproto/lexicon';
3
3
  export type QueryParams = Record<string, any>;
4
- export type Headers = Record<string, string>;
4
+ export type HeadersMap = Record<string, string>;
5
+ /** @deprecated not to be confused with the WHATWG Headers constructor */
6
+ export type Headers = HeadersMap;
7
+ export type Gettable<T> = T | (() => T);
5
8
  export interface CallOptions {
6
9
  encoding?: string;
7
- headers?: Headers;
10
+ signal?: AbortSignal;
11
+ headers?: HeadersMap;
8
12
  }
9
- export interface FetchHandlerResponse {
10
- status: number;
11
- headers: Headers;
12
- body: ArrayBuffer | undefined;
13
- }
14
- export type FetchHandler = (httpUri: string, httpMethod: string, httpHeaders: Headers, httpReqBody: any) => Promise<FetchHandlerResponse>;
15
13
  export declare const errorResponseBody: z.ZodObject<{
16
14
  error: z.ZodOptional<z.ZodString>;
17
15
  message: z.ZodOptional<z.ZodString>;
@@ -39,7 +37,9 @@ export declare enum ResponseType {
39
37
  NotEnoughResources = 503,
40
38
  UpstreamTimeout = 504
41
39
  }
40
+ export declare function httpResponseCodeToEnum(status: number): ResponseType;
42
41
  export declare const ResponseTypeNames: {
42
+ 1: string;
43
43
  2: string;
44
44
  200: string;
45
45
  400: string;
@@ -54,7 +54,9 @@ export declare const ResponseTypeNames: {
54
54
  503: string;
55
55
  504: string;
56
56
  };
57
+ export declare function httpResponseCodeToName(status: number): string;
57
58
  export declare const ResponseTypeStrings: {
59
+ 1: string;
58
60
  2: string;
59
61
  200: string;
60
62
  400: string;
@@ -69,6 +71,7 @@ export declare const ResponseTypeStrings: {
69
71
  503: string;
70
72
  504: string;
71
73
  };
74
+ export declare function httpResponseCodeToString(status: number): string;
72
75
  export declare class XRPCResponse {
73
76
  data: any;
74
77
  headers: Headers;
@@ -76,11 +79,12 @@ export declare class XRPCResponse {
76
79
  constructor(data: any, headers: Headers);
77
80
  }
78
81
  export declare class XRPCError extends Error {
79
- status: ResponseType;
80
- error?: string | undefined;
82
+ error: string;
83
+ headers?: HeadersMap | undefined;
81
84
  success: boolean;
82
- headers?: Headers;
83
- constructor(status: ResponseType, error?: string | undefined, message?: string, headers?: Headers);
85
+ status: ResponseType;
86
+ constructor(statusCode: number, error?: string, message?: string, headers?: HeadersMap | undefined, options?: ErrorOptions);
87
+ static from(cause: unknown, fallbackStatus?: ResponseType): XRPCError;
84
88
  }
85
89
  export declare class XRPCInvalidResponseError extends XRPCError {
86
90
  lexiconNsid: string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAElD,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;AAC7C,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;AAE5C,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,OAAO,CAAC,EAAE,OAAO,CAAA;CAClB;AAED,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,OAAO,CAAA;IAChB,IAAI,EAAE,WAAW,GAAG,SAAS,CAAA;CAC9B;AAED,MAAM,MAAM,YAAY,GAAG,CACzB,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,OAAO,EACpB,WAAW,EAAE,GAAG,KACb,OAAO,CAAC,oBAAoB,CAAC,CAAA;AAElC,eAAO,MAAM,iBAAiB;;;;;;;;;EAG5B,CAAA;AACF,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAA;AAE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IAOzB,KAAK,EAAE,MAAM;IAEb,OAAO,CAAC;IARjB,OAAO,UAAQ;IAER,MAAM,EAAE,YAAY,CAAA;gBAGzB,UAAU,EAAE,MAAM,EACX,KAAK,GAAE,MAA2C,EACzD,OAAO,CAAC,EAAE,MAAM,EACT,OAAO,CAAC,wBAAS,EACxB,OAAO,CAAC,EAAE,YAAY;IAaxB,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,cAAc,CAAC,EAAE,YAAY,GAAG,SAAS;CAsBtE;AAED,qBAAa,wBAAyB,SAAQ,SAAS;IAE5C,WAAW,EAAE,MAAM;IACnB,eAAe,EAAE,eAAe;IAChC,YAAY,EAAE,OAAO;gBAFrB,WAAW,EAAE,MAAM,EACnB,eAAe,EAAE,eAAe,EAChC,YAAY,EAAE,OAAO;CAU/B"}
package/dist/types.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.XRPCInvalidResponseError = exports.XRPCError = exports.XRPCResponse = exports.ResponseTypeStrings = exports.ResponseTypeNames = exports.ResponseType = exports.errorResponseBody = void 0;
3
+ exports.XRPCInvalidResponseError = exports.XRPCError = exports.XRPCResponse = exports.httpResponseCodeToString = exports.ResponseTypeStrings = exports.httpResponseCodeToName = exports.ResponseTypeNames = exports.httpResponseCodeToEnum = exports.ResponseType = exports.errorResponseBody = void 0;
4
4
  const zod_1 = require("zod");
5
5
  exports.errorResponseBody = zod_1.z.object({
6
6
  error: zod_1.z.string().optional(),
@@ -23,7 +23,29 @@ var ResponseType;
23
23
  ResponseType[ResponseType["NotEnoughResources"] = 503] = "NotEnoughResources";
24
24
  ResponseType[ResponseType["UpstreamTimeout"] = 504] = "UpstreamTimeout";
25
25
  })(ResponseType || (exports.ResponseType = ResponseType = {}));
26
+ function httpResponseCodeToEnum(status) {
27
+ if (status in ResponseType) {
28
+ return status;
29
+ }
30
+ else if (status >= 100 && status < 200) {
31
+ return ResponseType.XRPCNotSupported;
32
+ }
33
+ else if (status >= 200 && status < 300) {
34
+ return ResponseType.Success;
35
+ }
36
+ else if (status >= 300 && status < 400) {
37
+ return ResponseType.XRPCNotSupported;
38
+ }
39
+ else if (status >= 400 && status < 500) {
40
+ return ResponseType.InvalidRequest;
41
+ }
42
+ else {
43
+ return ResponseType.InternalServerError;
44
+ }
45
+ }
46
+ exports.httpResponseCodeToEnum = httpResponseCodeToEnum;
26
47
  exports.ResponseTypeNames = {
48
+ [ResponseType.Unknown]: 'Unknown',
27
49
  [ResponseType.InvalidResponse]: 'InvalidResponse',
28
50
  [ResponseType.Success]: 'Success',
29
51
  [ResponseType.InvalidRequest]: 'InvalidRequest',
@@ -38,7 +60,12 @@ exports.ResponseTypeNames = {
38
60
  [ResponseType.NotEnoughResources]: 'NotEnoughResources',
39
61
  [ResponseType.UpstreamTimeout]: 'UpstreamTimeout',
40
62
  };
63
+ function httpResponseCodeToName(status) {
64
+ return exports.ResponseTypeNames[httpResponseCodeToEnum(status)];
65
+ }
66
+ exports.httpResponseCodeToName = httpResponseCodeToName;
41
67
  exports.ResponseTypeStrings = {
68
+ [ResponseType.Unknown]: 'Unknown',
42
69
  [ResponseType.InvalidResponse]: 'Invalid Response',
43
70
  [ResponseType.Success]: 'Success',
44
71
  [ResponseType.InvalidRequest]: 'Invalid Request',
@@ -53,6 +80,10 @@ exports.ResponseTypeStrings = {
53
80
  [ResponseType.NotEnoughResources]: 'Not Enough Resources',
54
81
  [ResponseType.UpstreamTimeout]: 'Upstream Timeout',
55
82
  };
83
+ function httpResponseCodeToString(status) {
84
+ return exports.ResponseTypeStrings[httpResponseCodeToEnum(status)];
85
+ }
86
+ exports.httpResponseCodeToString = httpResponseCodeToString;
56
87
  class XRPCResponse {
57
88
  constructor(data, headers) {
58
89
  Object.defineProperty(this, "data", {
@@ -77,19 +108,19 @@ class XRPCResponse {
77
108
  }
78
109
  exports.XRPCResponse = XRPCResponse;
79
110
  class XRPCError extends Error {
80
- constructor(status, error, message, headers) {
81
- super(message || error || exports.ResponseTypeStrings[status]);
82
- Object.defineProperty(this, "status", {
111
+ constructor(statusCode, error = httpResponseCodeToName(statusCode), message, headers, options) {
112
+ super(message || error || httpResponseCodeToString(statusCode), options);
113
+ Object.defineProperty(this, "error", {
83
114
  enumerable: true,
84
115
  configurable: true,
85
116
  writable: true,
86
- value: status
117
+ value: error
87
118
  });
88
- Object.defineProperty(this, "error", {
119
+ Object.defineProperty(this, "headers", {
89
120
  enumerable: true,
90
121
  configurable: true,
91
122
  writable: true,
92
- value: error
123
+ value: headers
93
124
  });
94
125
  Object.defineProperty(this, "success", {
95
126
  enumerable: true,
@@ -97,22 +128,40 @@ class XRPCError extends Error {
97
128
  writable: true,
98
129
  value: false
99
130
  });
100
- Object.defineProperty(this, "headers", {
131
+ Object.defineProperty(this, "status", {
101
132
  enumerable: true,
102
133
  configurable: true,
103
134
  writable: true,
104
135
  value: void 0
105
136
  });
106
- if (!this.error) {
107
- this.error = exports.ResponseTypeNames[status];
137
+ this.status = httpResponseCodeToEnum(statusCode);
138
+ // Pre 2022 runtimes won't handle the "options" constructor argument
139
+ const cause = options?.cause;
140
+ if (this.cause === undefined && cause !== undefined) {
141
+ this.cause = cause;
142
+ }
143
+ }
144
+ static from(cause, fallbackStatus) {
145
+ if (cause instanceof XRPCError) {
146
+ return cause;
108
147
  }
109
- this.headers = headers;
148
+ // Extract status code from "http-errors" like errors
149
+ const statusCode = cause instanceof Error
150
+ ? ('statusCode' in cause ? cause.statusCode : undefined) ??
151
+ ('status' in cause ? cause.status : undefined)
152
+ : undefined;
153
+ const status = typeof statusCode === 'number'
154
+ ? httpResponseCodeToEnum(statusCode)
155
+ : fallbackStatus ?? ResponseType.Unknown;
156
+ const error = exports.ResponseTypeNames[status];
157
+ const message = cause instanceof Error ? cause.message : String(cause);
158
+ return new XRPCError(status, error, message, undefined, { cause });
110
159
  }
111
160
  }
112
161
  exports.XRPCError = XRPCError;
113
162
  class XRPCInvalidResponseError extends XRPCError {
114
163
  constructor(lexiconNsid, validationError, responseBody) {
115
- super(ResponseType.InvalidResponse, exports.ResponseTypeStrings[ResponseType.InvalidResponse], `The server gave an invalid response and may be out of date.`);
164
+ super(ResponseType.InvalidResponse, exports.ResponseTypeStrings[ResponseType.InvalidResponse], `The server gave an invalid response and may be out of date.`, undefined, { cause: validationError });
116
165
  Object.defineProperty(this, "lexiconNsid", {
117
166
  enumerable: true,
118
167
  configurable: true,