@atproto/lex-client 0.0.11 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/agent.d.ts +67 -0
  3. package/dist/agent.d.ts.map +1 -1
  4. package/dist/agent.js +31 -0
  5. package/dist/agent.js.map +1 -1
  6. package/dist/client.d.ts +438 -44
  7. package/dist/client.d.ts.map +1 -1
  8. package/dist/client.js +145 -1
  9. package/dist/client.js.map +1 -1
  10. package/dist/errors.d.ts +162 -9
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +132 -8
  13. package/dist/errors.js.map +1 -1
  14. package/dist/lexicons/com/atproto/repo/createRecord.defs.d.ts +20 -20
  15. package/dist/lexicons/com/atproto/repo/deleteRecord.defs.d.ts +12 -12
  16. package/dist/lexicons/com/atproto/repo/getRecord.defs.d.ts +6 -6
  17. package/dist/lexicons/com/atproto/repo/listRecords.defs.d.ts +6 -6
  18. package/dist/lexicons/com/atproto/repo/putRecord.defs.d.ts +22 -22
  19. package/dist/lexicons/com/atproto/repo/uploadBlob.defs.d.ts +2 -2
  20. package/dist/response.d.ts +14 -4
  21. package/dist/response.d.ts.map +1 -1
  22. package/dist/response.js +19 -9
  23. package/dist/response.js.map +1 -1
  24. package/dist/types.d.ts +51 -0
  25. package/dist/types.d.ts.map +1 -1
  26. package/dist/types.js.map +1 -1
  27. package/dist/util.d.ts +40 -5
  28. package/dist/util.d.ts.map +1 -1
  29. package/dist/util.js +22 -0
  30. package/dist/util.js.map +1 -1
  31. package/dist/www-authenticate.d.ts +23 -0
  32. package/dist/www-authenticate.d.ts.map +1 -1
  33. package/dist/www-authenticate.js.map +1 -1
  34. package/dist/xrpc.d.ts +81 -1
  35. package/dist/xrpc.d.ts.map +1 -1
  36. package/dist/xrpc.js.map +1 -1
  37. package/package.json +7 -7
  38. package/src/agent.ts +67 -0
  39. package/src/client.ts +420 -7
  40. package/src/errors.ts +165 -12
  41. package/src/response.ts +22 -19
  42. package/src/types.ts +52 -0
  43. package/src/util.ts +50 -5
  44. package/src/www-authenticate.ts +24 -0
  45. package/src/xrpc.ts +83 -4
@@ -16,13 +16,13 @@ declare const main: l.Query<"com.atproto.repo.getRecord", l.ParamsSchema<{
16
16
  readonly format: "cid";
17
17
  }>>;
18
18
  }>, l.Payload<"application/json", l.ObjectSchema<{
19
- readonly uri: l.StringSchema<{
19
+ uri: l.StringSchema<{
20
20
  readonly format: "at-uri";
21
21
  }>;
22
- readonly cid: l.OptionalSchema<l.StringSchema<{
22
+ cid: l.OptionalSchema<l.StringSchema<{
23
23
  readonly format: "cid";
24
24
  }>>;
25
- readonly value: l.UnknownObjectSchema;
25
+ value: l.UnknownObjectSchema;
26
26
  }>>, readonly ["RecordNotFound"]>;
27
27
  export { main };
28
28
  export type Params = l.InferMethodParams<typeof main>;
@@ -42,12 +42,12 @@ export declare const $lxm: "com.atproto.repo.getRecord", $params: l.ParamsSchema
42
42
  readonly format: "cid";
43
43
  }>>;
44
44
  }>, $output: l.Payload<"application/json", l.ObjectSchema<{
45
- readonly uri: l.StringSchema<{
45
+ uri: l.StringSchema<{
46
46
  readonly format: "at-uri";
47
47
  }>;
48
- readonly cid: l.OptionalSchema<l.StringSchema<{
48
+ cid: l.OptionalSchema<l.StringSchema<{
49
49
  readonly format: "cid";
50
50
  }>>;
51
- readonly value: l.UnknownObjectSchema;
51
+ value: l.UnknownObjectSchema;
52
52
  }>>;
53
53
  //# sourceMappingURL=getRecord.defs.d.ts.map
@@ -10,11 +10,11 @@ declare const main: l.Query<"com.atproto.repo.listRecords", l.ParamsSchema<{
10
10
  readonly format: "nsid";
11
11
  }>;
12
12
  readonly limit: l.OptionalSchema<l.WithDefaultSchema<l.IntegerSchema>>;
13
- readonly cursor: l.OptionalSchema<l.StringSchema<{}>>;
13
+ readonly cursor: l.OptionalSchema<l.StringSchema<l.StringSchemaOptions>>;
14
14
  readonly reverse: l.OptionalSchema<l.BooleanSchema>;
15
15
  }>, l.Payload<"application/json", l.ObjectSchema<{
16
- readonly cursor: l.OptionalSchema<l.StringSchema<{}>>;
17
- readonly records: l.ArraySchema<l.RefSchema<l.Validator<Record$0, Record$0>>>;
16
+ cursor: l.OptionalSchema<l.StringSchema<{}>>;
17
+ records: l.ArraySchema<l.RefSchema<l.Validator<Record$0, Record$0>>>;
18
18
  }>>, undefined>;
19
19
  export { main };
20
20
  export type Params = l.InferMethodParams<typeof main>;
@@ -28,11 +28,11 @@ export declare const $lxm: "com.atproto.repo.listRecords", $params: l.ParamsSche
28
28
  readonly format: "nsid";
29
29
  }>;
30
30
  readonly limit: l.OptionalSchema<l.WithDefaultSchema<l.IntegerSchema>>;
31
- readonly cursor: l.OptionalSchema<l.StringSchema<{}>>;
31
+ readonly cursor: l.OptionalSchema<l.StringSchema<l.StringSchemaOptions>>;
32
32
  readonly reverse: l.OptionalSchema<l.BooleanSchema>;
33
33
  }>, $output: l.Payload<"application/json", l.ObjectSchema<{
34
- readonly cursor: l.OptionalSchema<l.StringSchema<{}>>;
35
- readonly records: l.ArraySchema<l.RefSchema<l.Validator<Record$0, Record$0>>>;
34
+ cursor: l.OptionalSchema<l.StringSchema<{}>>;
35
+ records: l.ArraySchema<l.RefSchema<l.Validator<Record$0, Record$0>>>;
36
36
  }>>;
37
37
  type Record$0 = {
38
38
  $type?: 'com.atproto.repo.listRecords#record';
@@ -4,33 +4,33 @@ declare const $nsid = "com.atproto.repo.putRecord";
4
4
  export { $nsid };
5
5
  /** Write a repository record, creating or updating it as needed. Requires auth, implemented by PDS. */
6
6
  declare const main: l.Procedure<"com.atproto.repo.putRecord", l.ParamsSchema<{}>, l.Payload<"application/json", l.ObjectSchema<{
7
- readonly repo: l.StringSchema<{
7
+ repo: l.StringSchema<{
8
8
  readonly format: "at-identifier";
9
9
  }>;
10
- readonly collection: l.StringSchema<{
10
+ collection: l.StringSchema<{
11
11
  readonly format: "nsid";
12
12
  }>;
13
- readonly rkey: l.StringSchema<{
13
+ rkey: l.StringSchema<{
14
14
  readonly format: "record-key";
15
15
  readonly maxLength: 512;
16
16
  }>;
17
- readonly validate: l.OptionalSchema<l.BooleanSchema>;
18
- readonly record: l.UnknownObjectSchema;
19
- readonly swapRecord: l.OptionalSchema<l.NullableSchema<l.StringSchema<{
17
+ validate: l.OptionalSchema<l.BooleanSchema>;
18
+ record: l.UnknownObjectSchema;
19
+ swapRecord: l.OptionalSchema<l.NullableSchema<l.StringSchema<{
20
20
  readonly format: "cid";
21
21
  }>>>;
22
- readonly swapCommit: l.OptionalSchema<l.StringSchema<{
22
+ swapCommit: l.OptionalSchema<l.StringSchema<{
23
23
  readonly format: "cid";
24
24
  }>>;
25
25
  }>>, l.Payload<"application/json", l.ObjectSchema<{
26
- readonly uri: l.StringSchema<{
26
+ uri: l.StringSchema<{
27
27
  readonly format: "at-uri";
28
28
  }>;
29
- readonly cid: l.StringSchema<{
29
+ cid: l.StringSchema<{
30
30
  readonly format: "cid";
31
31
  }>;
32
- readonly commit: l.OptionalSchema<l.RefSchema<l.Validator<RepoDefs.CommitMeta, RepoDefs.CommitMeta>>>;
33
- readonly validationStatus: l.OptionalSchema<l.StringSchema<{}>>;
32
+ commit: l.OptionalSchema<l.RefSchema<l.Validator<RepoDefs.CommitMeta, RepoDefs.CommitMeta>>>;
33
+ validationStatus: l.OptionalSchema<l.StringSchema<{}>>;
34
34
  }>>, readonly ["InvalidSwap"]>;
35
35
  export { main };
36
36
  export type Params = l.InferMethodParams<typeof main>;
@@ -39,32 +39,32 @@ export type InputBody = l.InferMethodInputBody<typeof main>;
39
39
  export type Output = l.InferMethodOutput<typeof main>;
40
40
  export type OutputBody = l.InferMethodOutputBody<typeof main>;
41
41
  export declare const $lxm: "com.atproto.repo.putRecord", $params: l.ParamsSchema<{}>, $input: l.Payload<"application/json", l.ObjectSchema<{
42
- readonly repo: l.StringSchema<{
42
+ repo: l.StringSchema<{
43
43
  readonly format: "at-identifier";
44
44
  }>;
45
- readonly collection: l.StringSchema<{
45
+ collection: l.StringSchema<{
46
46
  readonly format: "nsid";
47
47
  }>;
48
- readonly rkey: l.StringSchema<{
48
+ rkey: l.StringSchema<{
49
49
  readonly format: "record-key";
50
50
  readonly maxLength: 512;
51
51
  }>;
52
- readonly validate: l.OptionalSchema<l.BooleanSchema>;
53
- readonly record: l.UnknownObjectSchema;
54
- readonly swapRecord: l.OptionalSchema<l.NullableSchema<l.StringSchema<{
52
+ validate: l.OptionalSchema<l.BooleanSchema>;
53
+ record: l.UnknownObjectSchema;
54
+ swapRecord: l.OptionalSchema<l.NullableSchema<l.StringSchema<{
55
55
  readonly format: "cid";
56
56
  }>>>;
57
- readonly swapCommit: l.OptionalSchema<l.StringSchema<{
57
+ swapCommit: l.OptionalSchema<l.StringSchema<{
58
58
  readonly format: "cid";
59
59
  }>>;
60
60
  }>>, $output: l.Payload<"application/json", l.ObjectSchema<{
61
- readonly uri: l.StringSchema<{
61
+ uri: l.StringSchema<{
62
62
  readonly format: "at-uri";
63
63
  }>;
64
- readonly cid: l.StringSchema<{
64
+ cid: l.StringSchema<{
65
65
  readonly format: "cid";
66
66
  }>;
67
- readonly commit: l.OptionalSchema<l.RefSchema<l.Validator<RepoDefs.CommitMeta, RepoDefs.CommitMeta>>>;
68
- readonly validationStatus: l.OptionalSchema<l.StringSchema<{}>>;
67
+ commit: l.OptionalSchema<l.RefSchema<l.Validator<RepoDefs.CommitMeta, RepoDefs.CommitMeta>>>;
68
+ validationStatus: l.OptionalSchema<l.StringSchema<{}>>;
69
69
  }>>;
70
70
  //# sourceMappingURL=putRecord.defs.d.ts.map
@@ -3,7 +3,7 @@ declare const $nsid = "com.atproto.repo.uploadBlob";
3
3
  export { $nsid };
4
4
  /** Upload a new blob, to be referenced from a repository record. The blob will be deleted if it is not referenced within a time window (eg, minutes). Blob restrictions (mimetype, size, etc) are enforced when the reference is created. Requires auth, implemented by PDS. */
5
5
  declare const main: l.Procedure<"com.atproto.repo.uploadBlob", l.ParamsSchema<{}>, l.Payload<"*/*", undefined>, l.Payload<"application/json", l.ObjectSchema<{
6
- readonly blob: l.BlobSchema<{
6
+ blob: l.BlobSchema<{
7
7
  allowLegacy: false;
8
8
  }>;
9
9
  }>>, undefined>;
@@ -14,7 +14,7 @@ export type InputBody = l.InferMethodInputBody<typeof main>;
14
14
  export type Output = l.InferMethodOutput<typeof main>;
15
15
  export type OutputBody = l.InferMethodOutputBody<typeof main>;
16
16
  export declare const $lxm: "com.atproto.repo.uploadBlob", $params: l.ParamsSchema<{}>, $input: l.Payload<"*/*", undefined>, $output: l.Payload<"application/json", l.ObjectSchema<{
17
- readonly blob: l.BlobSchema<{
17
+ blob: l.BlobSchema<{
18
18
  allowLegacy: false;
19
19
  }>;
20
20
  }>>;
@@ -1,7 +1,6 @@
1
- import { InferMethodOutputBody, InferMethodOutputEncoding, Procedure, Query, ResultSuccess } from '@atproto/lex-schema';
2
- import { XrpcPayload } from './util.js';
3
- export type XrpcResponseBody<M extends Procedure | Query> = InferMethodOutputBody<M, Uint8Array>;
4
- export type XrpcResponsePayload<M extends Procedure | Query> = InferMethodOutputEncoding<M> extends infer E extends string ? XrpcPayload<XrpcResponseBody<M>, E> : null;
1
+ import { InferMethodOutputEncoding, Procedure, Query, ResultSuccess } from '@atproto/lex-schema';
2
+ import { XrpcResponseBody, XrpcResponsePayload } from './util.js';
3
+ export type { XrpcResponseBody, XrpcResponsePayload };
5
4
  /**
6
5
  * Small container for XRPC response data.
7
6
  *
@@ -22,7 +21,18 @@ export declare class XrpcResponse<M extends Procedure | Query> implements Result
22
21
  * in binary form {@link Uint8Array} (`false`).
23
22
  */
24
23
  get isParsed(): boolean;
24
+ /**
25
+ * The Content-Type encoding of the response (e.g., 'application/json').
26
+ * Returns `undefined` if the response has no body.
27
+ */
25
28
  get encoding(): InferMethodOutputEncoding<M>;
29
+ /**
30
+ * The parsed response body.
31
+ *
32
+ * For 'application/json' responses, this is the parsed and validated LexValue.
33
+ * For binary responses, this is a Uint8Array.
34
+ * Returns `undefined` if the response has no body.
35
+ */
26
36
  get body(): XrpcResponseBody<M>;
27
37
  /**
28
38
  * @throws {XrpcResponseError} in case of (valid) XRPC error responses. Use
@@ -1 +1 @@
1
- {"version":3,"file":"response.d.ts","sourceRoot":"","sources":["../src/response.ts"],"names":[],"mappings":"AACA,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,SAAS,EACT,KAAK,EACL,aAAa,EACd,MAAM,qBAAqB,CAAA;AAO5B,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAEvC,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,IACtD,qBAAqB,CAAC,CAAC,EAAE,UAAU,CAAC,CAAA;AAEtC,MAAM,MAAM,mBAAmB,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,IACzD,yBAAyB,CAAC,CAAC,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM,GACvD,WAAW,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,GACnC,IAAI,CAAA;AAEV;;;;GAIG;AACH,qBAAa,YAAY,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,CACnD,YAAW,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IAWvC,QAAQ,CAAC,MAAM,EAAE,CAAC;IAClB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC;IAZ1C,yCAAyC;IACzC,QAAQ,CAAC,OAAO,EAAG,IAAI,CAAS;IAEhC,uCAAuC;IACvC,IAAI,KAAK,IAAI,IAAI,CAEhB;gBAGU,MAAM,EAAE,CAAC,EACT,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,CAAC,CAAC,CAAC;IAG1C;;;OAGG;IACH,IAAI,QAAQ,YAEX;IAED,IAAI,QAA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,CAAC,CAAC,CAAC,CAC9D;IAED;;;;;;OAMG;IACH,IAAI,IAAI,IACuB,gBAAgB,CAAC,CAAC,CAAC,CACjD;IAED;;;;;;;OAOG;WACU,iBAAiB,CAAC,KAAK,CAAC,CAAC,SAAS,SAAS,GAAG,KAAK,EAC9D,MAAM,EAAE,CAAC,EACT,QAAQ,EAAE,QAAQ,EAClB,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;KAAE,GACvC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;CAoG5B"}
package/dist/response.js CHANGED
@@ -3,6 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.XrpcResponse = void 0;
4
4
  const lex_json_1 = require("@atproto/lex-json");
5
5
  const errors_js_1 = require("./errors.js");
6
+ const CONTENT_TYPE_BINARY = 'application/octet-stream';
7
+ const CONTENT_TYPE_JSON = 'application/json';
6
8
  /**
7
9
  * Small container for XRPC response data.
8
10
  *
@@ -30,11 +32,22 @@ class XrpcResponse {
30
32
  * in binary form {@link Uint8Array} (`false`).
31
33
  */
32
34
  get isParsed() {
33
- return this.encoding === 'application/json' && shouldParse(this.method);
35
+ return this.method.output.encoding === CONTENT_TYPE_JSON;
34
36
  }
37
+ /**
38
+ * The Content-Type encoding of the response (e.g., 'application/json').
39
+ * Returns `undefined` if the response has no body.
40
+ */
35
41
  get encoding() {
36
42
  return this.payload?.encoding;
37
43
  }
44
+ /**
45
+ * The parsed response body.
46
+ *
47
+ * For 'application/json' responses, this is the parsed and validated LexValue.
48
+ * For binary responses, this is a Uint8Array.
49
+ * Returns `undefined` if the response has no body.
50
+ */
38
51
  get body() {
39
52
  return this.payload?.body;
40
53
  }
@@ -71,7 +84,7 @@ class XrpcResponse {
71
84
  }
72
85
  // Only parse json if the schema expects it
73
86
  const payload = await readPayload(response, {
74
- parse: shouldParse(method),
87
+ parse: method.output.encoding === CONTENT_TYPE_JSON,
75
88
  }).catch((cause) => {
76
89
  throw new errors_js_1.XrpcUpstreamError(method, response, null, 'Unable to parse response payload', { cause });
77
90
  });
@@ -101,9 +114,6 @@ class XrpcResponse {
101
114
  }
102
115
  }
103
116
  exports.XrpcResponse = XrpcResponse;
104
- function shouldParse(method) {
105
- return method.output.encoding === 'application/json';
106
- }
107
117
  /**
108
118
  * @note this function always consumes the response body
109
119
  */
@@ -117,17 +127,17 @@ async function readPayload(response, options) {
117
127
  .toLowerCase();
118
128
  // Response content-type is undefined
119
129
  if (!encoding) {
120
- // If the body is empty, return null (= no payload)
130
+ // If the body is empty, return undefined (= no payload)
121
131
  const body = await response.arrayBuffer();
122
132
  if (body.byteLength === 0)
123
- return null;
133
+ return undefined;
124
134
  // If we got data despite no content-type, treat it as binary
125
135
  return {
126
- encoding: 'application/octet-stream',
136
+ encoding: CONTENT_TYPE_BINARY,
127
137
  body: new Uint8Array(body),
128
138
  };
129
139
  }
130
- if (options?.parse && encoding === 'application/json') {
140
+ if (options?.parse && encoding === CONTENT_TYPE_JSON) {
131
141
  // @NOTE It might be worth returning the raw bytes here (Uint8Array) and
132
142
  // perform the lex parsing using cborg/json, allowing to do
133
143
  // bytes->LexValue in one step instead of bytes->text->JSON->LexValue.
@@ -1 +1 @@
1
- {"version":3,"file":"response.js","sourceRoot":"","sources":["../src/response.ts"],"names":[],"mappings":";;;AAAA,gDAA4C;AAQ5C,2CAKoB;AAWpB;;;;GAIG;AACH,MAAa,YAAY;IAYZ;IACA;IACA;IACA;IAZX,yCAAyC;IAChC,OAAO,GAAG,IAAa,CAAA;IAEhC,uCAAuC;IACvC,IAAI,KAAK;QACP,OAAO,IAAI,CAAA;IACb,CAAC;IAED,YACW,MAAS,EACT,MAAc,EACd,OAAgB,EAChB,OAA+B;QAH/B,WAAM,GAAN,MAAM,CAAG;QACT,WAAM,GAAN,MAAM,CAAQ;QACd,YAAO,GAAP,OAAO,CAAS;QAChB,YAAO,GAAP,OAAO,CAAwB;IACvC,CAAC;IAEJ;;;OAGG;IACH,IAAI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AAkB,EAAE,CAAC;QACtD,wEAAwE;QACxE,2DAA2D;QAC3D,sEAAsE;QACtE,yEAAyE;QACzE,qBAAqB;QACrB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAElC,sEAAsE;QACtE,mEAAmE;QACnE,6CAA6C;QAE7C,+BAA+B;QAC/B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAA,mBAAQ,EAAC,IAAI,CAAC,EAAE,CAAA;IAC3C,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC,EAAE,CAAA;AACzE,CAAC","sourcesContent":["import { lexParse } from '@atproto/lex-json'\nimport {\n InferMethodOutputBody,\n InferMethodOutputEncoding,\n Procedure,\n Query,\n ResultSuccess,\n} from '@atproto/lex-schema'\nimport {\n XrpcAuthenticationError,\n XrpcResponseError,\n XrpcUpstreamError,\n isXrpcErrorPayload,\n} from './errors.js'\nimport { XrpcPayload } from './util.js'\n\nexport type XrpcResponseBody<M extends Procedure | Query> =\n InferMethodOutputBody<M, Uint8Array>\n\nexport type XrpcResponsePayload<M extends Procedure | Query> =\n InferMethodOutputEncoding<M> extends infer E extends string\n ? XrpcPayload<XrpcResponseBody<M>, E>\n : null\n\n/**\n * Small container for XRPC response data.\n *\n * @implements {ResultSuccess<XrpcResponse<M>>} for convenience in result handling contexts.\n */\nexport class XrpcResponse<M extends Procedure | Query>\n implements ResultSuccess<XrpcResponse<M>>\n{\n /** @see {@link ResultSuccess.success} */\n readonly success = true as const\n\n /** @see {@link ResultSuccess.value} */\n get value(): this {\n return this\n }\n\n constructor(\n readonly method: M,\n readonly status: number,\n readonly headers: Headers,\n readonly payload: XrpcResponsePayload<M>,\n ) {}\n\n /**\n * Whether the response payload was parsed as {@link LexValue} (`true`) or is\n * in binary form {@link Uint8Array} (`false`).\n */\n get isParsed() {\n return this.encoding === 'application/json' && shouldParse(this.method)\n }\n\n get encoding() {\n return this.payload?.encoding as InferMethodOutputEncoding<M>\n }\n\n get body() {\n return this.payload?.body as XrpcResponseBody<M>\n }\n\n /**\n * @throws {XrpcResponseError} in case of (valid) XRPC error responses. Use\n * {@link XrpcResponseError.matchesSchema} to narrow the error type based on\n * the method's declared error schema. This can be narrowed further as a\n * {@link XrpcAuthenticationError} if the error is an authentication error.\n * @throws {XrpcUpstreamError} when the response is not a valid XRPC\n * response, or if the response does not conform to the method's schema.\n */\n static async fromFetchResponse<const M extends Procedure | Query>(\n method: M,\n response: Response,\n options?: { validateResponse?: boolean },\n ): Promise<XrpcResponse<M>> {\n // @NOTE The body MUST either be read or canceled to avoid resource leaks.\n // Since nothing should cause an exception before \"readPayload\" is\n // called, we can safely not use a try/finally here.\n\n // @NOTE redirect is set to 'follow', so we shouldn't get 3xx responses here\n if (response.status < 200 || response.status >= 300) {\n // Always parse json for error responses\n const payload = await readPayload(response, { parse: true }).catch(\n (cause) => {\n throw new XrpcUpstreamError(\n method,\n response,\n null,\n 'Unable to parse response payload',\n { cause },\n )\n },\n )\n\n // Properly formatted XRPC error response ?\n if (response.status >= 400 && isXrpcErrorPayload(payload)) {\n throw response.status === 401\n ? new XrpcAuthenticationError<M>(method, response, payload)\n : new XrpcResponseError<M>(method, response, payload)\n }\n\n // Invalid XRPC response (we probably did not hit an XRPC implementation)\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n response.status >= 500\n ? 'Upstream server encountered an error'\n : response.status >= 400\n ? 'Invalid response payload'\n : 'Invalid response status code',\n )\n }\n\n // Only parse json if the schema expects it\n const payload = await readPayload(response, {\n parse: shouldParse(method),\n }).catch((cause) => {\n throw new XrpcUpstreamError(\n method,\n response,\n null,\n 'Unable to parse response payload',\n { cause },\n )\n })\n\n // Response is successful (2xx). Validate payload (data and encoding) against schema.\n if (method.output.encoding == null) {\n // Schema expects no payload\n if (payload) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n `Expected response with no body, got ${payload.encoding}`,\n )\n }\n } else {\n // Schema expects a payload\n if (!payload || !method.output.matchesEncoding(payload.encoding)) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n payload\n ? `Expected ${method.output.encoding} response, got ${payload.encoding}`\n : `Expected non-empty response with content-type ${method.output.encoding}`,\n )\n }\n\n // Assert valid response body.\n if (method.output.schema && options?.validateResponse !== false) {\n const result = method.output.schema.safeParse(payload.body)\n\n if (!result.success) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n `Response validation failed: ${result.reason.message}`,\n { cause: result.reason },\n )\n }\n }\n }\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n payload as XrpcResponsePayload<M>,\n )\n }\n}\n\nfunction shouldParse(method: Procedure | Query) {\n return method.output.encoding === 'application/json'\n}\n\n/**\n * @note this function always consumes the response body\n */\nasync function readPayload(\n response: Response,\n options?: { parse?: boolean },\n): Promise<XrpcPayload | null> {\n // @TODO Should we limit the maximum response size here (this could also be\n // done by the FetchHandler)?\n\n const encoding = response.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n // Response content-type is undefined\n if (!encoding) {\n // If the body is empty, return null (= no payload)\n const body = await response.arrayBuffer()\n if (body.byteLength === 0) return null\n\n // If we got data despite no content-type, treat it as binary\n return {\n encoding: 'application/octet-stream',\n body: new Uint8Array(body),\n }\n }\n\n if (options?.parse && encoding === 'application/json') {\n // @NOTE It might be worth returning the raw bytes here (Uint8Array) and\n // perform the lex parsing using cborg/json, allowing to do\n // bytes->LexValue in one step instead of bytes->text->JSON->LexValue.\n // This would require adding encode/decode utilities to lex-json (similar\n // to @ipld/dag-json)\n const text = await response.text()\n\n // @NOTE Using `lexParse(text)` (instead of `jsonToLex(json)`) here as\n // using a reviver function during JSON.parse should be faster than\n // parsing to JSON then converting to Lex (?)\n\n // @TODO verify statement above\n return { encoding, body: lexParse(text) }\n }\n\n return { encoding, body: new Uint8Array(await response.arrayBuffer()) }\n}\n"]}
1
+ {"version":3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AAC;QACpB,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;SACd,IAAI,EAAE;SACN,WAAW,EAAE,CAAA;IAEhB,qCAAqC;IACrC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,wDAAwD;QACxD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAA;QACzC,IAAI,IAAI,CAAC,UAAU,KAAK,CAAC;YAAE,OAAO,SAAS,CAAA;QAE3C,6DAA6D;QAC7D,OAAO;YACL,QAAQ,EAAE,mBAAmB;YAC7B,IAAI,EAAE,IAAI,UAAU,CAAC,IAAI,CAAC;SAC3B,CAAA;IACH,CAAC;IAED,IAAI,OAAO,EAAE,KAAK,IAAI,QAAQ,KAAK,iBAAiB,EAAE,CAAC;QACrD,wEAAwE;QACxE,2DAA2D;QAC3D,sEAAsE;QACtE,yEAAyE;QACzE,qBAAqB;QACrB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAA;QAElC,sEAAsE;QACtE,mEAAmE;QACnE,6CAA6C;QAE7C,+BAA+B;QAC/B,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAA,mBAAQ,EAAC,IAAI,CAAC,EAAE,CAAA;IAC3C,CAAC;IAED,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,UAAU,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC,EAAE,CAAA;AACzE,CAAC","sourcesContent":["import { lexParse } from '@atproto/lex-json'\nimport {\n InferMethodOutputEncoding,\n Procedure,\n Query,\n ResultSuccess,\n} from '@atproto/lex-schema'\nimport {\n XrpcAuthenticationError,\n XrpcResponseError,\n XrpcUpstreamError,\n isXrpcErrorPayload,\n} from './errors.js'\nimport { XrpcResponseBody, XrpcResponsePayload } from './util.js'\n\nconst CONTENT_TYPE_BINARY = 'application/octet-stream'\nconst CONTENT_TYPE_JSON = 'application/json'\n\nexport type { XrpcResponseBody, XrpcResponsePayload }\n\n/**\n * Small container for XRPC response data.\n *\n * @implements {ResultSuccess<XrpcResponse<M>>} for convenience in result handling contexts.\n */\nexport class XrpcResponse<M extends Procedure | Query>\n implements ResultSuccess<XrpcResponse<M>>\n{\n /** @see {@link ResultSuccess.success} */\n readonly success = true as const\n\n /** @see {@link ResultSuccess.value} */\n get value(): this {\n return this\n }\n\n constructor(\n readonly method: M,\n readonly status: number,\n readonly headers: Headers,\n readonly payload: XrpcResponsePayload<M>,\n ) {}\n\n /**\n * Whether the response payload was parsed as {@link LexValue} (`true`) or is\n * in binary form {@link Uint8Array} (`false`).\n */\n get isParsed() {\n return this.method.output.encoding === CONTENT_TYPE_JSON\n }\n\n /**\n * The Content-Type encoding of the response (e.g., 'application/json').\n * Returns `undefined` if the response has no body.\n */\n get encoding() {\n return this.payload?.encoding as InferMethodOutputEncoding<M>\n }\n\n /**\n * The parsed response body.\n *\n * For 'application/json' responses, this is the parsed and validated LexValue.\n * For binary responses, this is a Uint8Array.\n * Returns `undefined` if the response has no body.\n */\n get body() {\n return this.payload?.body as XrpcResponseBody<M>\n }\n\n /**\n * @throws {XrpcResponseError} in case of (valid) XRPC error responses. Use\n * {@link XrpcResponseError.matchesSchema} to narrow the error type based on\n * the method's declared error schema. This can be narrowed further as a\n * {@link XrpcAuthenticationError} if the error is an authentication error.\n * @throws {XrpcUpstreamError} when the response is not a valid XRPC\n * response, or if the response does not conform to the method's schema.\n */\n static async fromFetchResponse<const M extends Procedure | Query>(\n method: M,\n response: Response,\n options?: { validateResponse?: boolean },\n ): Promise<XrpcResponse<M>> {\n // @NOTE The body MUST either be read or canceled to avoid resource leaks.\n // Since nothing should cause an exception before \"readPayload\" is\n // called, we can safely not use a try/finally here.\n\n // @NOTE redirect is set to 'follow', so we shouldn't get 3xx responses here\n if (response.status < 200 || response.status >= 300) {\n // Always parse json for error responses\n const payload = await readPayload(response, { parse: true }).catch(\n (cause) => {\n throw new XrpcUpstreamError(\n method,\n response,\n null,\n 'Unable to parse response payload',\n { cause },\n )\n },\n )\n\n // Properly formatted XRPC error response ?\n if (response.status >= 400 && isXrpcErrorPayload(payload)) {\n throw response.status === 401\n ? new XrpcAuthenticationError<M>(method, response, payload)\n : new XrpcResponseError<M>(method, response, payload)\n }\n\n // Invalid XRPC response (we probably did not hit an XRPC implementation)\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n response.status >= 500\n ? 'Upstream server encountered an error'\n : response.status >= 400\n ? 'Invalid response payload'\n : 'Invalid response status code',\n )\n }\n\n // Only parse json if the schema expects it\n const payload = await readPayload(response, {\n parse: method.output.encoding === CONTENT_TYPE_JSON,\n }).catch((cause) => {\n throw new XrpcUpstreamError(\n method,\n response,\n null,\n 'Unable to parse response payload',\n { cause },\n )\n })\n\n // Response is successful (2xx). Validate payload (data and encoding) against schema.\n if (method.output.encoding == null) {\n // Schema expects no payload\n if (payload) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n `Expected response with no body, got ${payload.encoding}`,\n )\n }\n } else {\n // Schema expects a payload\n if (!payload || !method.output.matchesEncoding(payload.encoding)) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n payload\n ? `Expected ${method.output.encoding} response, got ${payload.encoding}`\n : `Expected non-empty response with content-type ${method.output.encoding}`,\n )\n }\n\n // Assert valid response body.\n if (method.output.schema && options?.validateResponse !== false) {\n const result = method.output.schema.safeParse(payload.body)\n\n if (!result.success) {\n throw new XrpcUpstreamError(\n method,\n response,\n payload,\n `Response validation failed: ${result.reason.message}`,\n { cause: result.reason },\n )\n }\n }\n }\n\n return new XrpcResponse<M>(\n method,\n response.status,\n response.headers,\n payload as XrpcResponsePayload<M>,\n )\n }\n}\n\n/**\n * @note this function always consumes the response body\n */\nasync function readPayload(\n response: Response,\n options?: { parse?: boolean },\n): Promise<XrpcResponsePayload> {\n // @TODO Should we limit the maximum response size here (this could also be\n // done by the FetchHandler)?\n\n const encoding = response.headers\n .get('content-type')\n ?.split(';')[0]\n .trim()\n .toLowerCase()\n\n // Response content-type is undefined\n if (!encoding) {\n // If the body is empty, return undefined (= no payload)\n const body = await response.arrayBuffer()\n if (body.byteLength === 0) return undefined\n\n // If we got data despite no content-type, treat it as binary\n return {\n encoding: CONTENT_TYPE_BINARY,\n body: new Uint8Array(body),\n }\n }\n\n if (options?.parse && encoding === CONTENT_TYPE_JSON) {\n // @NOTE It might be worth returning the raw bytes here (Uint8Array) and\n // perform the lex parsing using cborg/json, allowing to do\n // bytes->LexValue in one step instead of bytes->text->JSON->LexValue.\n // This would require adding encode/decode utilities to lex-json (similar\n // to @ipld/dag-json)\n const text = await response.text()\n\n // @NOTE Using `lexParse(text)` (instead of `jsonToLex(json)`) here as\n // using a reviver function during JSON.parse should be faster than\n // parsing to JSON then converting to Lex (?)\n\n // @TODO verify statement above\n return { encoding, body: lexParse(text) }\n }\n\n return { encoding, body: new Uint8Array(await response.arrayBuffer()) }\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -1,11 +1,37 @@
1
1
  import { DidString, UnknownString } from '@atproto/lex-schema';
2
2
  export type { DidString, UnknownString };
3
+ /**
4
+ * Service identifier fragment for DID service endpoints.
5
+ *
6
+ * Common values include 'atproto_labeler' for labeling services,
7
+ * or custom service identifiers.
8
+ */
3
9
  export type DidServiceIdentifier = 'atproto_labeler' | UnknownString;
10
+ /**
11
+ * A full service proxy identifier combining a DID with a service fragment.
12
+ *
13
+ * Used to route requests through a specific service endpoint.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const service: Service = 'did:web:api.bsky.app#bsky_appview'
18
+ * ```
19
+ */
4
20
  export type Service = `${DidString}#${DidServiceIdentifier}`;
21
+ /**
22
+ * Common options available for all XRPC calls.
23
+ *
24
+ * These options can be passed to any method that makes XRPC requests,
25
+ * including `xrpc()`, `call()`, and record operations.
26
+ */
5
27
  export type CallOptions = {
28
+ /** Labeler DIDs to request labels from for content moderation. */
6
29
  labelers?: Iterable<DidString>;
30
+ /** AbortSignal to cancel the request. */
7
31
  signal?: AbortSignal;
32
+ /** Additional HTTP headers to include in the request. */
8
33
  headers?: HeadersInit;
34
+ /** Service proxy identifier for routing requests through a specific service. */
9
35
  service?: Service;
10
36
  /**
11
37
  * Whether to validate the request against the method's input schema. Enabling
@@ -27,5 +53,30 @@ export type CallOptions = {
27
53
  */
28
54
  validateResponse?: boolean;
29
55
  };
56
+ /**
57
+ * Valid input types for binary request bodies.
58
+ *
59
+ * These types can be used as the body for procedures that expect
60
+ * non-JSON content (e.g., blob uploads, binary data).
61
+ *
62
+ * @example Uploading a blob
63
+ * ```typescript
64
+ * const imageData: BinaryBodyInit = new Uint8Array(buffer)
65
+ * await client.uploadBlob(imageData, { encoding: 'image/png' })
66
+ * ```
67
+ *
68
+ * @example Streaming upload
69
+ * ```typescript
70
+ * const stream: BinaryBodyInit = someReadableStream
71
+ * await client.xrpc(uploadMethod, { body: stream })
72
+ * ```
73
+ *
74
+ * @example File upload in browser
75
+ * ```typescript
76
+ * const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
77
+ * const file: BinaryBodyInit = fileInput.files[0]
78
+ * await client.xrpc(uploadMethod, { body: file })
79
+ * ```
80
+ */
30
81
  export type BinaryBodyInit = Uint8Array | ArrayBuffer | Blob | ReadableStream<Uint8Array> | AsyncIterable<Uint8Array> | string;
31
82
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAE9D,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,CAAA;AAExC,MAAM,MAAM,oBAAoB,GAAG,iBAAiB,GAAG,aAAa,CAAA;AACpE,MAAM,MAAM,OAAO,GAAG,GAAG,SAAS,IAAI,oBAAoB,EAAE,CAAA;AAE5D,MAAM,MAAM,WAAW,GAAG;IACxB,QAAQ,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAA;IAC9B,MAAM,CAAC,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a,CAAC,UAAU,CAAC,GACzB,MAAM,CAAA"}
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import { DidString, UnknownString } from '@atproto/lex-schema'\n\nexport type { DidString, UnknownString }\n\nexport type DidServiceIdentifier = 'atproto_labeler' | UnknownString\nexport type Service = `${DidString}#${DidServiceIdentifier}`\n\nexport type CallOptions = {\n labelers?: Iterable<DidString>\n signal?: AbortSignal\n headers?: HeadersInit\n service?: Service\n\n /**\n * Whether to validate the request against the method's input schema. Enabling\n * this can help catch errors early but may have a performance cost. This\n * would typically only be set to `true` in development or debugging\n * scenarios.\n *\n * @default false\n */\n validateRequest?: boolean\n\n /**\n * Whether to validate the response against the method's output schema.\n * Disabling this can improve performance but may lead to runtime errors if\n * the response does not conform to the expected schema. Only set this to\n * `false` if you are certain that the upstream service will always return\n * valid responses.\n *\n * @default true\n */\n validateResponse?: boolean\n}\n\nexport type BinaryBodyInit =\n | Uint8Array\n | ArrayBuffer\n | Blob\n | ReadableStream<Uint8Array>\n | AsyncIterable<Uint8Array>\n | string\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import { DidString, UnknownString } from '@atproto/lex-schema'\n\nexport type { DidString, UnknownString }\n\n/**\n * Service identifier fragment for DID service endpoints.\n *\n * Common values include 'atproto_labeler' for labeling services,\n * or custom service identifiers.\n */\nexport type DidServiceIdentifier = 'atproto_labeler' | UnknownString\n\n/**\n * A full service proxy identifier combining a DID with a service fragment.\n *\n * Used to route requests through a specific service endpoint.\n *\n * @example\n * ```typescript\n * const service: Service = 'did:web:api.bsky.app#bsky_appview'\n * ```\n */\nexport type Service = `${DidString}#${DidServiceIdentifier}`\n\n/**\n * Common options available for all XRPC calls.\n *\n * These options can be passed to any method that makes XRPC requests,\n * including `xrpc()`, `call()`, and record operations.\n */\nexport type CallOptions = {\n /** Labeler DIDs to request labels from for content moderation. */\n labelers?: Iterable<DidString>\n /** AbortSignal to cancel the request. */\n signal?: AbortSignal\n /** Additional HTTP headers to include in the request. */\n headers?: HeadersInit\n /** Service proxy identifier for routing requests through a specific service. */\n service?: Service\n\n /**\n * Whether to validate the request against the method's input schema. Enabling\n * this can help catch errors early but may have a performance cost. This\n * would typically only be set to `true` in development or debugging\n * scenarios.\n *\n * @default false\n */\n validateRequest?: boolean\n\n /**\n * Whether to validate the response against the method's output schema.\n * Disabling this can improve performance but may lead to runtime errors if\n * the response does not conform to the expected schema. Only set this to\n * `false` if you are certain that the upstream service will always return\n * valid responses.\n *\n * @default true\n */\n validateResponse?: boolean\n}\n\n/**\n * Valid input types for binary request bodies.\n *\n * These types can be used as the body for procedures that expect\n * non-JSON content (e.g., blob uploads, binary data).\n *\n * @example Uploading a blob\n * ```typescript\n * const imageData: BinaryBodyInit = new Uint8Array(buffer)\n * await client.uploadBlob(imageData, { encoding: 'image/png' })\n * ```\n *\n * @example Streaming upload\n * ```typescript\n * const stream: BinaryBodyInit = someReadableStream\n * await client.xrpc(uploadMethod, { body: stream })\n * ```\n *\n * @example File upload in browser\n * ```typescript\n * const fileInput = document.querySelector('input[type=\"file\"]') as HTMLInputElement\n * const file: BinaryBodyInit = fileInput.files[0]\n * await client.xrpc(uploadMethod, { body: file })\n * ```\n */\nexport type BinaryBodyInit =\n | Uint8Array\n | ArrayBuffer\n | Blob\n | ReadableStream<Uint8Array>\n | AsyncIterable<Uint8Array>\n | string\n"]}
package/dist/util.d.ts CHANGED
@@ -1,10 +1,45 @@
1
- import { DidString } from '@atproto/lex-schema';
2
- export type XrpcPayload<B = unknown, E extends string = string> = {
3
- body: B;
4
- encoding: E;
5
- };
1
+ import { DidString, InferMethodOutput, InferMethodOutputBody, Procedure, Query } from '@atproto/lex-schema';
2
+ /**
3
+ * The body type of an XRPC response, inferred from the method's output schema.
4
+ *
5
+ * For JSON responses, this is the parsed LexValue. For binary responses,
6
+ * this is a Uint8Array.
7
+ *
8
+ * @typeParam M - The XRPC method type (Procedure or Query)
9
+ */
10
+ export type XrpcResponseBody<M extends Procedure | Query = Procedure | Query> = InferMethodOutputBody<M, Uint8Array>;
11
+ /**
12
+ * The full payload type of an XRPC response, including body and encoding.
13
+ *
14
+ * Returns `null` for methods that have no output.
15
+ *
16
+ * @typeParam M - The XRPC method type (Procedure or Query)
17
+ */
18
+ export type XrpcResponsePayload<M extends Procedure | Query = Procedure | Query> = InferMethodOutput<M, Uint8Array>;
19
+ /**
20
+ * Type guard to check if a value is {@link Blob}-like.
21
+ *
22
+ * Handles both native Blobs and polyfilled Blob implementations
23
+ * (e.g., fetch-blob from node-fetch).
24
+ *
25
+ * @param value - The value to check
26
+ * @returns `true` if the value is a Blob or Blob-like object
27
+ */
6
28
  export declare function isBlobLike(value: unknown): value is Blob;
7
29
  export declare function isAsyncIterable<T>(value: T): value is unknown extends T ? T & AsyncIterable<unknown> : Extract<T, AsyncIterable<any>>;
30
+ /**
31
+ * Builds HTTP headers for AT Protocol requests.
32
+ *
33
+ * Adds the following headers when applicable:
34
+ * - `atproto-proxy`: Service routing header (if service is specified)
35
+ * - `atproto-accept-labelers`: Comma-separated list of labeler DIDs
36
+ *
37
+ * @param options - Header building options
38
+ * @param options.headers - Base headers to include
39
+ * @param options.service - Service proxy identifier
40
+ * @param options.labelers - Labeler DIDs to request labels from
41
+ * @returns A new Headers object with AT Protocol headers added
42
+ */
8
43
  export declare function buildAtprotoHeaders(options: {
9
44
  headers?: HeadersInit;
10
45
  service?: `${DidString}#${string}`;
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAE/C,MAAM,MAAM,WAAW,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IAChE,IAAI,EAAE,CAAC,CAAA;IACP,QAAQ,EA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AC,EAC/B,KAAK,EAAE,CAAC,GACP,KAAK,IAAI,OAAO,SAAS,CAAC,GACzB,CAAC,GAAG,aAAa,CAAC,OAAO,CAAC,GAC1B,OAAO,CAAC,CAAC,EAAE,aAAa,CAAC,GAAG,CAAC,CAAC,CAIjC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAC3C,OAAO,CAAC,EAAE,WAAW,CAAA;IACrB,OAAO,CAAC,EAAE,GAAG,SAAS,IAAI,MAAM,EAAE,CAAA;IAClC,QAAQ,CAAC,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAA;CAC/B,GAAG,OAAO,CAiBV;AAED,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,aAAa,CAAC,UAAU,CAAC,GAC9B,cAAc,CAAC,UAAU,CAAC,CAwB5B"}
package/dist/util.js CHANGED
@@ -4,6 +4,15 @@ exports.isBlobLike = isBlobLike;
4
4
  exports.isAsyncIterable = isAsyncIterable;
5
5
  exports.buildAtprotoHeaders = buildAtprotoHeaders;
6
6
  exports.toReadableStream = toReadableStream;
7
+ /**
8
+ * Type guard to check if a value is {@link Blob}-like.
9
+ *
10
+ * Handles both native Blobs and polyfilled Blob implementations
11
+ * (e.g., fetch-blob from node-fetch).
12
+ *
13
+ * @param value - The value to check
14
+ * @returns `true` if the value is a Blob or Blob-like object
15
+ */
7
16
  function isBlobLike(value) {
8
17
  if (value == null)
9
18
  return false;
@@ -23,6 +32,19 @@ function isBlobLike(value) {
23
32
  function isAsyncIterable(value) {
24
33
  return (value != null && typeof value[Symbol.asyncIterator] === 'function');
25
34
  }
35
+ /**
36
+ * Builds HTTP headers for AT Protocol requests.
37
+ *
38
+ * Adds the following headers when applicable:
39
+ * - `atproto-proxy`: Service routing header (if service is specified)
40
+ * - `atproto-accept-labelers`: Comma-separated list of labeler DIDs
41
+ *
42
+ * @param options - Header building options
43
+ * @param options.headers - Base headers to include
44
+ * @param options.service - Service proxy identifier
45
+ * @param options.labelers - Labeler DIDs to request labels from
46
+ * @returns A new Headers object with AT Protocol headers added
47
+ */
26
48
  function buildAtprotoHeaders(options) {
27
49
  const headers = new Headers(options?.headers);
28
50
  if (options.service && !headers.has('atproto-proxy')) {
package/dist/util.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;AAOA,gCAeC;AAED,0CAQC;AAED,kDAqBC;AAED,4CA0BC;AA5ED,SAAgB,UAAU,CAAC,KAAc;IACvC,IAAI,KAAK,IAAI,IAAI;QAAE,OAAO,KAAK,CAAA;IAC/B,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAA;IAC3C,IAAI,OAAO,IAAI,KAAK,UAAU,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,IAAI,CAAA;IAEpE,yEAAyE;IACzE,qCAAqC;IACrC,4GAA4G;IAE5G,MAAM,GAAG,GAAI,KAAa,CAAC,MAAM,CAAC,WAAW,CAAC,CAAA;IAC9C,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;QACrC,OAAO,QAAQ,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,CAAA;IAChE,CAAC;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAED,SAAgB,eAAe,CAC7B,KAAQ;IAIR,OAAO,CACL,KAAK,IAAI,IAAI,IAAI,OAAQ,KAAa,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,UAAU,CAC5E,CAAA;AACH,CAAC;AAED,SAAgB,mBAAmB,CAAC,OAInC;IACC,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,CAAA;IAE7C,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,EAAE,CAAC;QACrD,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,OAAO,CAAC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export type XrpcPayload<B = unknown, E extends string = string> = {\n body: B\n encoding: E\n}\n\nexport function isBlobLike(value: unknown): value is Blob {\n if (value == null) return false\n if (typeof value !== 'object') return false\n if (typeof Blob === 'function' && value instanceof Blob) return true\n\n // Support for Blobs provided by libraries that don't use the native Blob\n // (e.g. fetch-blob from node-fetch).\n // https://github.com/node-fetch/fetch-blob/blob/a1a182e5978811407bef4ea1632b517567dda01f/index.js#L233-L244\n\n const tag = (value as any)[Symbol.toStringTag]\n if (tag === 'Blob' || tag === 'File') {\n return 'stream' in value && typeof value.stream === 'function'\n }\n\n return false\n}\n\nexport function isAsyncIterable<T>(\n value: T,\n): value is unknown extends T\n ? T & AsyncIterable<unknown>\n : Extract<T, AsyncIterable<any>> {\n return (\n value != null && typeof (value as any)[Symbol.asyncIterator] === 'function'\n )\n}\n\nexport function buildAtprotoHeaders(options: {\n headers?: HeadersInit\n service?: `${DidString}#${string}`\n labelers?: Iterable<DidString>\n}): Headers {\n const headers = new Headers(options?.headers)\n\n if (options.service && !headers.has('atproto-proxy')) {\n headers.set('atproto-proxy', options.service)\n }\n\n if (options.labelers) {\n headers.set(\n 'atproto-accept-labelers',\n [...options.labelers, headers.get('atproto-accept-labelers')?.trim()]\n .filter(Boolean)\n .join(', '),\n )\n }\n\n return headers\n}\n\nexport function toReadableStream(\n data: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n // Use the native ReadableStream.from() if available.\n if ('from' in ReadableStream && typeof ReadableStream.from === 'function') {\n return ReadableStream.from(data)\n }\n\n let iterator: AsyncIterator<Uint8Array> | undefined\n return new ReadableStream({\n async pull(controller) {\n try {\n iterator ??= data[Symbol.asyncIterator]()\n const result = await iterator!.next()\n if (result.done) controller.close()\n else controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n iterator = undefined\n }\n },\n async cancel() {\n await iterator?.return?.()\n iterator = undefined\n },\n })\n}\n"]}
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[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B,CAAC,EAAE,IAAI,EAAE,CAAC;aAClE,MAAM,CAAC,OAAO,CAAC;aACf,IAAI,CAAC,IAAI,CAAC,CACd,CAAA;IACH,CAAC;IAED,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,SAAgB,gBAAgB,CAC9B,IAA+B;IAE/B,qDAAqD;IACrD,IAAI,MAAM,IAAI,cAAc,IAAI,OAAO,cAAc,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC1E,OAAO,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAClC,CAAC;IAED,IAAI,QAA+C,CAAA;IACnD,OAAO,IAAI,cAAc,CAAC;QACxB,KAAK,CAAC,IAAI,CAAC,UAAU;YACnB,IAAI,CAAC;gBACH,QAAQ,KAAK,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAA;gBACzC,MAAM,MAAM,GAAG,MAAM,QAAS,CAAC,IAAI,EAAE,CAAA;gBACrC,IAAI,MAAM,CAAC,IAAI;oBAAE,UAAU,CAAC,KAAK,EAAE,CAAA;;oBAC9B,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;YACvC,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;gBACrB,QAAQ,GAAG,SAAS,CAAA;YACtB,CAAC;QACH,CAAC;QACD,KAAK,CAAC,MAAM;YACV,MAAM,QAAQ,EAAE,MAAM,EAAE,EAAE,CAAA;YAC1B,QAAQ,GAAG,SAAS,CAAA;QACtB,CAAC;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {\n DidString,\n InferMethodOutput,\n InferMethodOutputBody,\n Procedure,\n Query,\n} from '@atproto/lex-schema'\n\n/**\n * The body type of an XRPC response, inferred from the method's output schema.\n *\n * For JSON responses, this is the parsed LexValue. For binary responses,\n * this is a Uint8Array.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponseBody<M extends Procedure | Query = Procedure | Query> =\n InferMethodOutputBody<M, Uint8Array>\n\n/**\n * The full payload type of an XRPC response, including body and encoding.\n *\n * Returns `null` for methods that have no output.\n *\n * @typeParam M - The XRPC method type (Procedure or Query)\n */\nexport type XrpcResponsePayload<\n M extends Procedure | Query = Procedure | Query,\n> = InferMethodOutput<M, Uint8Array>\n\n/**\n * Type guard to check if a value is {@link Blob}-like.\n *\n * Handles both native Blobs and polyfilled Blob implementations\n * (e.g., fetch-blob from node-fetch).\n *\n * @param value - The value to check\n * @returns `true` if the value is a Blob or Blob-like object\n */\nexport function isBlobLike(value: unknown): value is Blob {\n if (value == null) return false\n if (typeof value !== 'object') return false\n if (typeof Blob === 'function' && value instanceof Blob) return true\n\n // Support for Blobs provided by libraries that don't use the native Blob\n // (e.g. fetch-blob from node-fetch).\n // https://github.com/node-fetch/fetch-blob/blob/a1a182e5978811407bef4ea1632b517567dda01f/index.js#L233-L244\n\n const tag = (value as any)[Symbol.toStringTag]\n if (tag === 'Blob' || tag === 'File') {\n return 'stream' in value && typeof value.stream === 'function'\n }\n\n return false\n}\n\nexport function isAsyncIterable<T>(\n value: T,\n): value is unknown extends T\n ? T & AsyncIterable<unknown>\n : Extract<T, AsyncIterable<any>> {\n return (\n value != null && typeof (value as any)[Symbol.asyncIterator] === 'function'\n )\n}\n\n/**\n * Builds HTTP headers for AT Protocol requests.\n *\n * Adds the following headers when applicable:\n * - `atproto-proxy`: Service routing header (if service is specified)\n * - `atproto-accept-labelers`: Comma-separated list of labeler DIDs\n *\n * @param options - Header building options\n * @param options.headers - Base headers to include\n * @param options.service - Service proxy identifier\n * @param options.labelers - Labeler DIDs to request labels from\n * @returns A new Headers object with AT Protocol headers added\n */\nexport function buildAtprotoHeaders(options: {\n headers?: HeadersInit\n service?: `${DidString}#${string}`\n labelers?: Iterable<DidString>\n}): Headers {\n const headers = new Headers(options?.headers)\n\n if (options.service && !headers.has('atproto-proxy')) {\n headers.set('atproto-proxy', options.service)\n }\n\n if (options.labelers) {\n headers.set(\n 'atproto-accept-labelers',\n [...options.labelers, headers.get('atproto-accept-labelers')?.trim()]\n .filter(Boolean)\n .join(', '),\n )\n }\n\n return headers\n}\n\nexport function toReadableStream(\n data: AsyncIterable<Uint8Array>,\n): ReadableStream<Uint8Array> {\n // Use the native ReadableStream.from() if available.\n if ('from' in ReadableStream && typeof ReadableStream.from === 'function') {\n return ReadableStream.from(data)\n }\n\n let iterator: AsyncIterator<Uint8Array> | undefined\n return new ReadableStream({\n async pull(controller) {\n try {\n iterator ??= data[Symbol.asyncIterator]()\n const result = await iterator!.next()\n if (result.done) controller.close()\n else controller.enqueue(result.value)\n } catch (err) {\n controller.error(err)\n iterator = undefined\n }\n },\n async cancel() {\n await iterator?.return?.()\n iterator = undefined\n },\n })\n}\n"]}
@@ -1,6 +1,29 @@
1
1
  type WWWAuthenticateParams = {
2
2
  [authParam in string]: string;
3
3
  };
4
+ /**
5
+ * Parsed representation of a WWW-Authenticate HTTP header.
6
+ *
7
+ * Maps authentication scheme names to either:
8
+ * - A token68 string (compact authentication data)
9
+ * - A params object with key-value pairs
10
+ *
11
+ * @example Bearer with realm
12
+ * ```typescript
13
+ * // WWW-Authenticate: Bearer realm="example"
14
+ * const parsed: WWWAuthenticate = {
15
+ * Bearer: { realm: 'example' }
16
+ * }
17
+ * ```
18
+ *
19
+ * @example DPoP with error
20
+ * ```typescript
21
+ * // WWW-Authenticate: DPoP error="use_dpop_nonce", error_description="..."
22
+ * const parsed: WWWAuthenticate = {
23
+ * DPoP: { error: 'use_dpop_nonce', error_description: '...' }
24
+ * }
25
+ * ```
26
+ */
4
27
  export type WWWAuthenticate = {
5
28
  [authScheme in string]: string | WWWAuthenticateParams;
6
29
  };
@@ -1 +1 @@
1
- {"version":3,"file":"www-authenticate.d.ts","sourceRoot":"","sources":["../src/www-authenticate.ts"],"names":[],"mappings":"AAAA,KAAK,qBAAqB,GAAG;KAAG,SAAS,IAAI,MAAM,GAAG,MAAM;CAAE,CAAA;AAC9D,MAAM,MAAM,eAAe,GAAG;KAC3B,UAAU,IAAI,MAAM,GACjB,MAAM,GACN,qBAAqB;CAC1B,CAAA;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,CAAC,EAAE,OAAO,GACf,SAAS,GAAG,eAAe,CAgE7B"}
1
+ {"version":3,"file":"www-authenticate.d.ts","sourceRoot":"","sources":["../src/www-authenticate.ts"],"names":[],"mappings":"AAAA,KAAK,qBAAqB,GAAG;KAAG,SAAS,IAAI,MAAM,GAAG,MAAM;CAAE,CAAA;AAE9D;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,eAAe,GAAG;KAC3B,UAAU,IAAI,MAAM,GACjB,MAAM,GACN,qBAAqB;CAC1B,CAAA;AAED;;GAEG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,CAAC,EAAE,OAAO,GACf,SAAS,GAAG,eAAe,CAgE7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"www-authenticate.js","sourceRoot":"","sources":["../src/www-authenticate.ts"],"names":[],"mappings":";;AAUA,gEAkEC;AArED;;GAEG;AACH,SAAgB,0BAA0B,CACxC,MAAgB;IAEhB,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,SAAS,CAAA;IAEhD,MAAM,eAAe,GAAoB,EAAE,CAAA;IAE3C,+CAA+C;IAC/C,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,EAAE,CAAA;IACnC,IAAI,CAAC,aAAa;QAAE,OAAO,eAAe,CAAA;IAE1C,MAAM,KAAK,GAAG,aAAa,CAAC,KAAK,CAAC,8BAA8B,CAAC,CAAA;IAEjE,IAAI,aAAa,GAAiC,IAAI,CAAA;IAEtD,KAAK,IAAI,IAAI,IAAI,KAAK,EAAE,CAAC;QACvB,+CAA+C;QAC/C,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,sBAAsB,CAAC,CAAA;QAC7D,IAAI,WAAW,EAAE,CA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C,SAAS,CAAC,GAAG,UAAU,CAAA;IACvC,CAAC;IAED,OAAO,eAAe,CAAA;AACxB,CAAC","sourcesContent":["type WWWAuthenticateParams = { [authParam in string]: string }\nexport type WWWAuthenticate = {\n [authScheme in string]:\n | string // token68\n | WWWAuthenticateParams\n}\n\n/**\n * Returns `undefined` if the header is malformed.\n */\nexport function parseWWWAuthenticateHeader(\n header?: unknown,\n): undefined | WWWAuthenticate {\n if (typeof header !== 'string') return undefined\n\n const wwwAuthenticate: WWWAuthenticate = {}\n\n // Split over commas, not within quoted strings\n const trimmedHeader = header.trim()\n if (!trimmedHeader) return wwwAuthenticate\n\n const parts = trimmedHeader.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/)\n\n let currentParams: WWWAuthenticateParams | null = null\n\n for (let part of parts) {\n // Check if the part starts with an auth scheme\n const schemeMatch = part.trim().match(/^([^\"=\\s]+)(\\s+.*)?$/)\n if (schemeMatch) {\n const scheme = schemeMatch[1]\n\n // Duplicate scheme\n if (Object.hasOwn(wwwAuthenticate, scheme)) return undefined\n\n const rest = schemeMatch[2]?.trim()\n if (!rest) {\n // Scheme only (no params or token68)\n currentParams = null\n wwwAuthenticate[scheme] = Object.create(null)\n continue\n }\n\n if (!rest.includes('=')) {\n // Scheme with token68\n currentParams = null\n wwwAuthenticate[scheme] = rest\n continue\n }\n\n // Scheme with params\n\n currentParams = Object.create(null) as WWWAuthenticateParams\n wwwAuthenticate[scheme] = currentParams\n\n // Fall through to parse params\n part = rest\n }\n\n // Invalid header\n if (!currentParams) return undefined\n\n const param = part.match(\n /^\\s*([^\"\\s=]+)=(?:(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|([^\\s,\"]*))\\s*$/,\n )\n\n // invalid param\n if (!param) return undefined\n\n const paramName = param[1]\n const paramValue =\n param[3] ?? param[2]!.slice(1, -1).replaceAll(/\\\\(.)/g, '$1')\n\n currentParams[paramName] = paramValue\n }\n\n return wwwAuthenticate\n}\n"]}
1
+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AQ;YACV,CAAC;YAED,qBAAqB;YAErB,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAA0B,CAAA;YAC5D,eAAe,CAAC,MAAM,CAAC,GAAG,aAAa,CAAA;YAEvC,+BAA+B;YAC/B,IAAI,GAAG,IAAI,CAAA;QACb,CAAC;QAED,iBAAiB;QACjB,IAAI,CAAC,aAAa;YAAE,OAAO,SAAS,CAAA;QAEpC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CACtB,8DAA8D,CAC/D,CAAA;QAED,gBAAgB;QAChB,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAA;QAE5B,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAA;QAC1B,MAAM,UAAU,GACd,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,CAAE,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;QAE/D,aAAa,CAAC,SAAS,CAAC,GAAG,UAAU,CAAA;IACvC,CAAC;IAED,OAAO,eAAe,CAAA;AACxB,CAAC","sourcesContent":["type WWWAuthenticateParams = { [authParam in string]: string }\n\n/**\n * Parsed representation of a WWW-Authenticate HTTP header.\n *\n * Maps authentication scheme names to either:\n * - A token68 string (compact authentication data)\n * - A params object with key-value pairs\n *\n * @example Bearer with realm\n * ```typescript\n * // WWW-Authenticate: Bearer realm=\"example\"\n * const parsed: WWWAuthenticate = {\n * Bearer: { realm: 'example' }\n * }\n * ```\n *\n * @example DPoP with error\n * ```typescript\n * // WWW-Authenticate: DPoP error=\"use_dpop_nonce\", error_description=\"...\"\n * const parsed: WWWAuthenticate = {\n * DPoP: { error: 'use_dpop_nonce', error_description: '...' }\n * }\n * ```\n */\nexport type WWWAuthenticate = {\n [authScheme in string]:\n | string // token68\n | WWWAuthenticateParams\n}\n\n/**\n * Returns `undefined` if the header is malformed.\n */\nexport function parseWWWAuthenticateHeader(\n header?: unknown,\n): undefined | WWWAuthenticate {\n if (typeof header !== 'string') return undefined\n\n const wwwAuthenticate: WWWAuthenticate = {}\n\n // Split over commas, not within quoted strings\n const trimmedHeader = header.trim()\n if (!trimmedHeader) return wwwAuthenticate\n\n const parts = trimmedHeader.split(/,(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/)\n\n let currentParams: WWWAuthenticateParams | null = null\n\n for (let part of parts) {\n // Check if the part starts with an auth scheme\n const schemeMatch = part.trim().match(/^([^\"=\\s]+)(\\s+.*)?$/)\n if (schemeMatch) {\n const scheme = schemeMatch[1]\n\n // Duplicate scheme\n if (Object.hasOwn(wwwAuthenticate, scheme)) return undefined\n\n const rest = schemeMatch[2]?.trim()\n if (!rest) {\n // Scheme only (no params or token68)\n currentParams = null\n wwwAuthenticate[scheme] = Object.create(null)\n continue\n }\n\n if (!rest.includes('=')) {\n // Scheme with token68\n currentParams = null\n wwwAuthenticate[scheme] = rest\n continue\n }\n\n // Scheme with params\n\n currentParams = Object.create(null) as WWWAuthenticateParams\n wwwAuthenticate[scheme] = currentParams\n\n // Fall through to parse params\n part = rest\n }\n\n // Invalid header\n if (!currentParams) return undefined\n\n const param = part.match(\n /^\\s*([^\"\\s=]+)=(?:(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|([^\\s,\"]*))\\s*$/,\n )\n\n // invalid param\n if (!param) return undefined\n\n const paramName = param[1]\n const paramValue =\n param[3] ?? param[2]!.slice(1, -1).replaceAll(/\\\\(.)/g, '$1')\n\n currentParams[paramName] = paramValue\n }\n\n return wwwAuthenticate\n}\n"]}