@orpc/client 2.0.0-beta.49 → 2.0.0-beta.50

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 (75) hide show
  1. package/dist/adapters/fetch/index.d.ts +3 -2
  2. package/dist/adapters/fetch/index.js +2 -2
  3. package/dist/adapters/fetch/rpc-link.d.ts +8 -8
  4. package/dist/adapters/fetch/rpc-link.js +16 -13
  5. package/dist/adapters/fetch/transport.d.ts +29 -31
  6. package/dist/adapters/fetch/transport.js +49 -63
  7. package/dist/adapters/message-port/index.d.ts +4 -3
  8. package/dist/adapters/message-port/index.js +3 -3
  9. package/dist/adapters/message-port/message-port.d.ts +13 -13
  10. package/dist/adapters/message-port/message-port.js +35 -53
  11. package/dist/adapters/message-port/rpc-link.d.ts +8 -8
  12. package/dist/adapters/message-port/rpc-link.js +17 -14
  13. package/dist/adapters/message-port/transport.d.ts +31 -34
  14. package/dist/adapters/message-port/transport.js +38 -52
  15. package/dist/adapters/standard/codec.d.ts +10 -10
  16. package/dist/adapters/standard/index.d.ts +6 -5
  17. package/dist/adapters/standard/index.js +2 -4
  18. package/dist/adapters/standard/link.d.ts +31 -31
  19. package/dist/adapters/standard/link.js +101 -85
  20. package/dist/adapters/standard/plugin.d.ts +25 -31
  21. package/dist/adapters/standard/plugin.js +14 -16
  22. package/dist/adapters/standard/rpc-link-codec.d.ts +53 -60
  23. package/dist/adapters/standard/rpc-link-codec.js +98 -102
  24. package/dist/adapters/standard/transport.d.ts +7 -7
  25. package/dist/adapters/websocket/index.d.ts +3 -2
  26. package/dist/adapters/websocket/index.js +2 -2
  27. package/dist/adapters/websocket/rpc-link.d.ts +8 -8
  28. package/dist/adapters/websocket/rpc-link.js +16 -13
  29. package/dist/adapters/websocket/transport.d.ts +101 -100
  30. package/dist/adapters/websocket/transport.js +102 -130
  31. package/dist/async-iterator-object.d.ts +2 -2
  32. package/dist/async-iterator-object.js +27 -28
  33. package/dist/client-safe.d.ts +4 -6
  34. package/dist/client-safe.js +29 -34
  35. package/dist/client.d.ts +24 -26
  36. package/dist/client.js +35 -37
  37. package/dist/consts.d.ts +1 -1
  38. package/dist/consts.js +18 -41
  39. package/dist/dynamic-link.d.ts +6 -6
  40. package/dist/dynamic-link.js +16 -16
  41. package/dist/error-utils.d.ts +3 -4
  42. package/dist/error-utils.js +47 -51
  43. package/dist/error.d.ts +79 -79
  44. package/dist/error.js +154 -166
  45. package/dist/index.d.ts +14 -53
  46. package/dist/index.js +12 -40
  47. package/dist/plugins/batch.d.ts +122 -155
  48. package/dist/plugins/batch.js +320 -391
  49. package/dist/plugins/cookie-jar.d.ts +64 -61
  50. package/dist/plugins/cookie-jar.js +208 -245
  51. package/dist/plugins/dedupe.d.ts +49 -53
  52. package/dist/plugins/dedupe.js +168 -211
  53. package/dist/plugins/index.d.ts +9 -28
  54. package/dist/plugins/index.js +8 -23
  55. package/dist/plugins/request-compression.d.ts +38 -35
  56. package/dist/plugins/request-compression.js +131 -177
  57. package/dist/plugins/response-compression.d.ts +21 -18
  58. package/dist/plugins/response-compression.js +64 -88
  59. package/dist/plugins/retry-after.d.ts +31 -38
  60. package/dist/plugins/retry-after.js +60 -85
  61. package/dist/plugins/retry.d.ts +55 -55
  62. package/dist/plugins/retry.js +118 -137
  63. package/dist/plugins/timeout.d.ts +19 -17
  64. package/dist/plugins/timeout.js +41 -36
  65. package/dist/rpc-json-serializer.d.ts +84 -84
  66. package/dist/rpc-json-serializer.js +338 -383
  67. package/dist/rpc-serializer.d.ts +20 -21
  68. package/dist/rpc-serializer.js +97 -125
  69. package/dist/types.d.ts +19 -31
  70. package/dist/utils.d.ts +18 -29
  71. package/dist/utils.js +63 -47
  72. package/package.json +5 -5
  73. package/dist/adapters/standard/codec.js +0 -1
  74. package/dist/adapters/standard/transport.js +0 -1
  75. package/dist/types.js +0 -1
@@ -1,28 +1,31 @@
1
- import type { StandardLinkOptions, StandardLinkPlugin, StandardLinkTransportInterceptorOptions } from '../adapters/standard/index.ts';
2
- import type { ClientContext } from '../types.ts';
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkOptions, StandardLinkTransportInterceptorOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { CompressionEncoding } from "@orpc/shared";
3
6
  export interface RequestCompressionLinkPluginOptions<T extends ClientContext> {
4
- /**
5
- * The compression scheme to use for request compression.
6
- *
7
- * @default 'gzip'
8
- */
9
- encoding?: 'gzip' | 'deflate' | 'deflate-raw' | undefined;
10
- /**
11
- * The minimum request size in bytes required to trigger compression.
12
- * Requests smaller than this threshold will not be compressed to avoid overhead.
13
- * If the request size cannot be determined, compression will still be applied.
14
- *
15
- * @default 1024 (1KB)
16
- */
17
- threshold?: number | undefined;
18
- /**
19
- * Determines whether a request with the given Content-Type should be compressed.
20
- * Only consulted for binary transfers (streams, files, and file form-data parts).
21
- * Also receives the transport interceptor options for per-request decisions.
22
- *
23
- * @default isCompressibleContentType (covers common text-based formats)
24
- */
25
- isCompressibleContentType?: ((contentType: string | null | undefined, options: StandardLinkTransportInterceptorOptions<T>) => boolean) | undefined;
7
+ /**
8
+ * The compression scheme to use for request compression.
9
+ *
10
+ * @default 'gzip'
11
+ */
12
+ encoding?: CompressionEncoding | undefined;
13
+ /**
14
+ * The minimum request size in bytes required to trigger compression.
15
+ * Requests smaller than this threshold will not be compressed to avoid overhead.
16
+ * If the request size cannot be determined, compression will still be applied.
17
+ *
18
+ * @default 1024 (1KB)
19
+ */
20
+ threshold?: number | undefined;
21
+ /**
22
+ * Determines whether a request with the given Content-Type should be compressed.
23
+ * Only consulted for binary transfers (streams, files, and file form-data parts).
24
+ * Also receives the transport interceptor options for per-request decisions.
25
+ *
26
+ * @default isCompressibleContentType (covers common text-based formats)
27
+ */
28
+ isCompressibleContentType?: ((contentType: string | null | undefined, options: StandardLinkTransportInterceptorOptions<T>) => boolean) | undefined;
26
29
  }
27
30
  /**
28
31
  * Compresses request bodies before sending them to the server,
@@ -31,14 +34,14 @@ export interface RequestCompressionLinkPluginOptions<T extends ClientContext> {
31
34
  * @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
32
35
  */
33
36
  export declare class RequestCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
34
- name: string;
35
- /**
36
- * Compression should be done after batching, to compress the final request
37
- */
38
- after: string[];
39
- private readonly encoding;
40
- private readonly threshold;
41
- private readonly isCompressibleContentType;
42
- constructor(options?: RequestCompressionLinkPluginOptions<T>);
43
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
44
- }
37
+ name: string;
38
+ /**
39
+ * Compression should be done after batching, to compress the final request
40
+ */
41
+ after: string[];
42
+ private readonly encoding;
43
+ private readonly threshold;
44
+ private readonly isCompressibleContentType;
45
+ constructor(options?: RequestCompressionLinkPluginOptions<T>);
46
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
47
+ }
@@ -1,178 +1,132 @@
1
- import { isAsyncIteratorObject, isCompressibleContentType, toArray } from '@orpc/shared';
2
- import { flattenStandardHeader, generateContentDisposition } from '@standard-server/core';
3
- import { toFetchBody } from '@standard-server/fetch';
4
- // Rough UTF-8 estimate. Mostly ASCII text stays close to 1 byte/char;
5
- // occasional multi-byte characters increase the average.
6
- const AVG_BYTES_PER_CHAR = 1.2;
1
+ import { estimateCompressibleFormDataSize, estimateUtf8ByteLength, isAsyncIteratorObject, isCompressibleContentType, toArray } from "@orpc/shared";
2
+ import { flattenStandardHeader, generateContentDisposition } from "@standard-server/core";
3
+ import { toFetchBody } from "@standard-server/fetch";
4
+ // src/plugins/request-compression.ts
7
5
  /**
8
- * Compresses request bodies before sending them to the server,
9
- * reducing bandwidth usage for large payloads.
10
- *
11
- * @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
12
- */
13
- export class RequestCompressionLinkPlugin {
14
- name = '~request-compression';
15
- /**
16
- * Compression should be done after batching, to compress the final request
17
- */
18
- after = ['~batch'];
19
- encoding;
20
- threshold;
21
- isCompressibleContentType;
22
- constructor(options = {}) {
23
- this.encoding = options.encoding ?? 'gzip';
24
- this.threshold = options.threshold ?? 1024;
25
- this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
26
- }
27
- init(options) {
28
- const transportInterceptor = async ({ next, ...interceptorOptions }) => {
29
- const request = interceptorOptions.request;
30
- const contentEncoding = flattenStandardHeader(request.headers['content-encoding'])
31
- ?.trim()
32
- ?.toLowerCase();
33
- if (contentEncoding !== undefined) {
34
- // already compressed, do not compress again
35
- return next();
36
- }
37
- if (request.body instanceof ReadableStream) {
38
- const contentLength = Number(flattenStandardHeader(request.headers['content-length']));
39
- if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) &&
40
- this.isCompressibleContentType(flattenStandardHeader(request.headers['content-type']), interceptorOptions)) {
41
- const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
42
- return next({
43
- ...interceptorOptions,
44
- request: {
45
- ...interceptorOptions.request,
46
- body: compressedStream,
47
- headers: {
48
- ...request.headers,
49
- 'content-length': [],
50
- 'content-encoding': this.encoding,
51
- },
52
- },
53
- });
54
- }
55
- }
56
- else if (request.body instanceof Blob) {
57
- const contentType = request.headers['content-type'] ?? request.body.type;
58
- if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) &&
59
- this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
60
- const compressedStream = request.body
61
- .stream()
62
- .pipeThrough(new CompressionStream(this.encoding));
63
- const contentDisposition = request.headers['content-disposition'] ??
64
- generateContentDisposition(request.body instanceof File ? request.body.name : 'blob');
65
- return next({
66
- ...interceptorOptions,
67
- request: {
68
- ...interceptorOptions.request,
69
- body: compressedStream,
70
- headers: {
71
- ...request.headers,
72
- 'standard-server': request.headers['standard-server'] ?? 'file',
73
- 'content-type': contentType,
74
- 'content-length': [],
75
- 'content-disposition': contentDisposition,
76
- 'content-encoding': this.encoding,
77
- },
78
- },
79
- });
80
- }
81
- }
82
- else if (request.body instanceof FormData) {
83
- const PART_OVERHEAD = 64; // approx bytes for boundary + Content-Disposition/Content-Type headers per part
84
- let contentLength = 0;
85
- for (const [key, value] of request.body) {
86
- contentLength += PART_OVERHEAD + key.length;
87
- if (value instanceof Blob) {
88
- if (!Number.isFinite(value.size)) {
89
- // Bun-s3 can use NaN for size
90
- if (!this.isCompressibleContentType(value.type, interceptorOptions)) {
91
- // Unknown non-compressible part size makes the estimate unreliable
92
- contentLength = -Infinity;
93
- break;
94
- }
95
- // Unknown size for compressible content - still apply compression
96
- contentLength = Infinity;
97
- }
98
- else {
99
- contentLength += this.isCompressibleContentType(value.type, interceptorOptions)
100
- ? value.size
101
- : -value.size;
102
- }
103
- }
104
- else {
105
- contentLength += value.length * AVG_BYTES_PER_CHAR;
106
- }
107
- }
108
- if (contentLength >= this.threshold) {
109
- const res = new Response(request.body);
110
- const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
111
- return next({
112
- ...interceptorOptions,
113
- request: {
114
- ...interceptorOptions.request,
115
- body: compressedStream,
116
- headers: {
117
- ...request.headers,
118
- 'standard-server': [],
119
- 'content-type': res.headers.get('content-type'),
120
- 'content-length': [],
121
- 'content-encoding': this.encoding,
122
- },
123
- },
124
- });
125
- }
126
- }
127
- else if (request.body instanceof URLSearchParams) {
128
- const string = request.body.toString();
129
- if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
130
- const compressedStream = new Blob([string])
131
- .stream()
132
- .pipeThrough(new CompressionStream(this.encoding));
133
- const [, bodyHeaders] = toFetchBody(request.body, request.headers);
134
- return next({
135
- ...interceptorOptions,
136
- request: {
137
- ...interceptorOptions.request,
138
- body: compressedStream,
139
- headers: {
140
- ...bodyHeaders,
141
- // An empty hint rather than none, so the adapter does not hint the compressed stream as `octet-stream`
142
- 'standard-server': bodyHeaders['standard-server'] ?? [],
143
- 'content-length': [],
144
- 'content-encoding': this.encoding,
145
- },
146
- },
147
- });
148
- }
149
- }
150
- else if (request.body !== undefined && !isAsyncIteratorObject(request.body)) {
151
- const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
152
- if (string.length * AVG_BYTES_PER_CHAR >= this.threshold) {
153
- const compressedStream = new Blob([string])
154
- .stream()
155
- .pipeThrough(new CompressionStream(this.encoding));
156
- return next({
157
- ...interceptorOptions,
158
- request: {
159
- ...interceptorOptions.request,
160
- body: compressedStream,
161
- headers: {
162
- ...bodyHeaders,
163
- 'standard-server': bodyHeaders['standard-server'] ?? [],
164
- 'content-length': [],
165
- 'content-encoding': this.encoding,
166
- },
167
- },
168
- });
169
- }
170
- }
171
- return next();
172
- };
173
- return {
174
- ...options,
175
- transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
176
- };
177
- }
178
- }
6
+ * Compresses request bodies before sending them to the server,
7
+ * reducing bandwidth usage for large payloads.
8
+ *
9
+ * @see {@link https://orpc.dev/docs/plugins/request-compression | Request Compression Plugin}
10
+ */
11
+ var RequestCompressionLinkPlugin = class {
12
+ name = "~request-compression";
13
+ /**
14
+ * Compression should be done after batching, to compress the final request
15
+ */
16
+ after = ["~batch"];
17
+ encoding;
18
+ threshold;
19
+ isCompressibleContentType;
20
+ constructor(options = {}) {
21
+ this.encoding = options.encoding ?? "gzip";
22
+ this.threshold = options.threshold ?? 1024;
23
+ this.isCompressibleContentType = options.isCompressibleContentType ?? isCompressibleContentType;
24
+ }
25
+ init(options) {
26
+ const transportInterceptor = async ({ next, ...interceptorOptions }) => {
27
+ const request = interceptorOptions.request;
28
+ if (flattenStandardHeader(request.headers["content-encoding"])?.trim()?.toLowerCase() !== void 0) return next();
29
+ if (request.body instanceof ReadableStream) {
30
+ const contentLength = Number(flattenStandardHeader(request.headers["content-length"]));
31
+ if ((!Number.isFinite(contentLength) || contentLength >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(request.headers["content-type"]), interceptorOptions)) {
32
+ const compressedStream = request.body.pipeThrough(new CompressionStream(this.encoding));
33
+ return next({
34
+ ...interceptorOptions,
35
+ request: {
36
+ ...interceptorOptions.request,
37
+ body: compressedStream,
38
+ headers: {
39
+ ...request.headers,
40
+ "content-length": [],
41
+ "content-encoding": this.encoding
42
+ }
43
+ }
44
+ });
45
+ }
46
+ } else if (request.body instanceof Blob) {
47
+ const contentType = request.headers["content-type"] ?? request.body.type;
48
+ if ((!Number.isFinite(request.body.size) || request.body.size >= this.threshold) && this.isCompressibleContentType(flattenStandardHeader(contentType), interceptorOptions)) {
49
+ const compressedStream = request.body.stream().pipeThrough(new CompressionStream(this.encoding));
50
+ const contentDisposition = request.headers["content-disposition"] ?? generateContentDisposition(request.body instanceof File ? request.body.name : "blob");
51
+ return next({
52
+ ...interceptorOptions,
53
+ request: {
54
+ ...interceptorOptions.request,
55
+ body: compressedStream,
56
+ headers: {
57
+ ...request.headers,
58
+ "standard-server": request.headers["standard-server"] ?? "file",
59
+ "content-type": contentType,
60
+ "content-length": [],
61
+ "content-disposition": contentDisposition,
62
+ "content-encoding": this.encoding
63
+ }
64
+ }
65
+ });
66
+ }
67
+ } else if (request.body instanceof FormData) {
68
+ if (estimateCompressibleFormDataSize(request.body, (contentType) => this.isCompressibleContentType(contentType, interceptorOptions)) >= this.threshold) {
69
+ const res = new Response(request.body);
70
+ const compressedStream = res.body.pipeThrough(new CompressionStream(this.encoding));
71
+ return next({
72
+ ...interceptorOptions,
73
+ request: {
74
+ ...interceptorOptions.request,
75
+ body: compressedStream,
76
+ headers: {
77
+ ...request.headers,
78
+ "standard-server": [],
79
+ "content-type": res.headers.get("content-type"),
80
+ "content-length": [],
81
+ "content-encoding": this.encoding
82
+ }
83
+ }
84
+ });
85
+ }
86
+ } else if (request.body instanceof URLSearchParams) {
87
+ const string = request.body.toString();
88
+ if (estimateUtf8ByteLength(string) >= this.threshold) {
89
+ const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
90
+ const [, bodyHeaders] = toFetchBody(request.body, request.headers);
91
+ return next({
92
+ ...interceptorOptions,
93
+ request: {
94
+ ...interceptorOptions.request,
95
+ body: compressedStream,
96
+ headers: {
97
+ ...bodyHeaders,
98
+ "standard-server": bodyHeaders["standard-server"] ?? [],
99
+ "content-length": [],
100
+ "content-encoding": this.encoding
101
+ }
102
+ }
103
+ });
104
+ }
105
+ } else if (request.body !== void 0 && !isAsyncIteratorObject(request.body)) {
106
+ const [string, bodyHeaders] = toFetchBody(request.body, request.headers);
107
+ if (estimateUtf8ByteLength(string) >= this.threshold) {
108
+ const compressedStream = new Blob([string]).stream().pipeThrough(new CompressionStream(this.encoding));
109
+ return next({
110
+ ...interceptorOptions,
111
+ request: {
112
+ ...interceptorOptions.request,
113
+ body: compressedStream,
114
+ headers: {
115
+ ...bodyHeaders,
116
+ "standard-server": bodyHeaders["standard-server"] ?? [],
117
+ "content-length": [],
118
+ "content-encoding": this.encoding
119
+ }
120
+ }
121
+ });
122
+ }
123
+ }
124
+ return next();
125
+ };
126
+ return {
127
+ ...options,
128
+ transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
129
+ };
130
+ }
131
+ };
132
+ export { RequestCompressionLinkPlugin };
@@ -1,13 +1,16 @@
1
- import type { StandardLinkOptions, StandardLinkPlugin } from '../adapters/standard/index.ts';
2
- import type { ClientContext } from '../types.ts';
1
+ import "../adapters/standard/index.js";
2
+ import { StandardLinkPlugin } from "../adapters/standard/plugin.js";
3
+ import { StandardLinkOptions } from "../adapters/standard/link.js";
4
+ import { ClientContext } from "../types.js";
5
+ import { CompressionEncoding } from "@orpc/shared";
3
6
  export interface ResponseCompressionLinkPluginOptions<_T extends ClientContext> {
4
- /**
5
- * Compression schemes to advertise via Accept-Encoding, in preference order.
6
- * Only schemes that can be decompressed by this plugin should be listed.
7
- *
8
- * @default ['gzip', 'deflate']
9
- */
10
- encodings?: readonly ('gzip' | 'deflate' | 'deflate-raw')[] | undefined;
7
+ /**
8
+ * Compression schemes to advertise via Accept-Encoding, in preference order.
9
+ * Only schemes that can be decompressed by this plugin should be listed.
10
+ *
11
+ * @default ['gzip', 'deflate']
12
+ */
13
+ encodings?: readonly CompressionEncoding[] | undefined;
11
14
  }
12
15
  /**
13
16
  * Advertises Accept-Encoding on requests and decompresses response bodies
@@ -17,12 +20,12 @@ export interface ResponseCompressionLinkPluginOptions<_T extends ClientContext>
17
20
  * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
18
21
  */
19
22
  export declare class ResponseCompressionLinkPlugin<T extends ClientContext> implements StandardLinkPlugin<T> {
20
- name: string;
21
- /**
22
- * Decompression should wrap the final batch response instead of sub-responses.
23
- */
24
- after: string[];
25
- private readonly encodings;
26
- constructor(options?: ResponseCompressionLinkPluginOptions<T>);
27
- init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
28
- }
23
+ name: string;
24
+ /**
25
+ * Decompression should wrap the final batch response instead of sub-responses.
26
+ */
27
+ after: string[];
28
+ private readonly encodings;
29
+ constructor(options?: ResponseCompressionLinkPluginOptions<T>);
30
+ init(options: StandardLinkOptions<T>): StandardLinkOptions<T>;
31
+ }
@@ -1,91 +1,67 @@
1
- import { toArray } from '@orpc/shared';
2
- import { flattenStandardHeader } from '@standard-server/core';
3
- import { toFetchHeaders, toStandardBody } from '@standard-server/fetch';
1
+ import { isCompressionEncoding, parseContentEncodings, toArray } from "@orpc/shared";
2
+ import { flattenStandardHeader } from "@standard-server/core";
3
+ import { toFetchHeaders, toStandardBody } from "@standard-server/fetch";
4
+ // src/plugins/response-compression.ts
4
5
  /**
5
- * Each coding adds a decompressor to the chain, so an unbounded list lets a tiny
6
- * response cost unbounded CPU and memory. Same limit as undici and curl.
7
- */
6
+ * Each coding adds a decompressor to the chain, so an unbounded list lets a tiny
7
+ * response cost unbounded CPU and memory. Same limit as undici and curl.
8
+ */
8
9
  const MAX_CONTENT_ENCODINGS = 5;
9
10
  /**
10
- * Advertises Accept-Encoding on requests and decompresses response bodies
11
- * based on the Content-Encoding header. Works at the standard link level,
12
- * so it supports all adapters.
13
- *
14
- * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
15
- */
16
- export class ResponseCompressionLinkPlugin {
17
- name = '~response-compression';
18
- /**
19
- * Decompression should wrap the final batch response instead of sub-responses.
20
- */
21
- after = ['~batch'];
22
- encodings;
23
- constructor(options = {}) {
24
- this.encodings = options.encodings ?? ['gzip', 'deflate'];
25
- }
26
- init(options) {
27
- const acceptEncodingHeader = this.encodings.join(', ');
28
- const transportInterceptor = async ({ next, ...interceptorOptions }) => {
29
- const response = await next({
30
- ...interceptorOptions,
31
- request: {
32
- ...interceptorOptions.request,
33
- headers: {
34
- ...interceptorOptions.request.headers,
35
- 'accept-encoding': acceptEncodingHeader,
36
- },
37
- },
38
- });
39
- const encodings = parseContentEncodings(flattenStandardHeader(response.headers['content-encoding']));
40
- if (encodings.length === 0 || !encodings.every(isSupportedEncoding)) {
41
- return response;
42
- }
43
- const decompressedHeaders = {
44
- ...response.headers,
45
- 'content-length': undefined,
46
- 'content-encoding': undefined,
47
- };
48
- return {
49
- ...response,
50
- headers: decompressedHeaders,
51
- async resolveBody(hint) {
52
- const stream = await response.resolveBody('octet-stream');
53
- // adapter might not support hint (e.g. peer adapter)
54
- if (!(stream instanceof ReadableStream)) {
55
- return stream;
56
- }
57
- if (encodings.length > MAX_CONTENT_ENCODINGS) {
58
- throw new TypeError('Too many content encodings.');
59
- }
60
- let decompressedStream = stream;
61
- for (let i = encodings.length - 1; i >= 0; i--) {
62
- decompressedStream = decompressedStream.pipeThrough(new DecompressionStream(encodings[i]));
63
- }
64
- const fetchResponse = new Response(decompressedStream, {
65
- headers: toFetchHeaders(decompressedHeaders),
66
- });
67
- return toStandardBody(fetchResponse, { hint });
68
- },
69
- };
70
- };
71
- return {
72
- ...options,
73
- transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor],
74
- };
75
- }
76
- }
77
- const SUPPORTED_ENCODINGS = ['gzip', 'deflate', 'deflate-raw'];
78
- function isSupportedEncoding(encoding) {
79
- return SUPPORTED_ENCODINGS.includes(encoding);
80
- }
81
- /**
82
- * Parse Content-Encoding into ordered codings (order applied).
83
- *
84
- * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-content-encoding
85
- */
86
- function parseContentEncodings(header) {
87
- if (header === undefined) {
88
- return [];
89
- }
90
- return header.split(',').map((part) => part.trim().toLowerCase());
91
- }
11
+ * Advertises Accept-Encoding on requests and decompresses response bodies
12
+ * based on the Content-Encoding header. Works at the standard link level,
13
+ * so it supports all adapters.
14
+ *
15
+ * @see {@link https://orpc.dev/docs/plugins/response-compression | Response Compression Plugin}
16
+ */
17
+ var ResponseCompressionLinkPlugin = class {
18
+ name = "~response-compression";
19
+ /**
20
+ * Decompression should wrap the final batch response instead of sub-responses.
21
+ */
22
+ after = ["~batch"];
23
+ encodings;
24
+ constructor(options = {}) {
25
+ this.encodings = options.encodings ?? ["gzip", "deflate"];
26
+ }
27
+ init(options) {
28
+ const acceptEncodingHeader = this.encodings.join(", ");
29
+ const transportInterceptor = async ({ next, ...interceptorOptions }) => {
30
+ const response = await next({
31
+ ...interceptorOptions,
32
+ request: {
33
+ ...interceptorOptions.request,
34
+ headers: {
35
+ ...interceptorOptions.request.headers,
36
+ "accept-encoding": acceptEncodingHeader
37
+ }
38
+ }
39
+ });
40
+ const encodings = parseContentEncodings(flattenStandardHeader(response.headers["content-encoding"]));
41
+ if (encodings.length === 0 || !encodings.every(isCompressionEncoding)) return response;
42
+ const decompressedHeaders = {
43
+ ...response.headers,
44
+ "content-length": void 0,
45
+ "content-encoding": void 0
46
+ };
47
+ return {
48
+ ...response,
49
+ headers: decompressedHeaders,
50
+ async resolveBody(hint) {
51
+ const stream = await response.resolveBody("octet-stream");
52
+ if (!(stream instanceof ReadableStream)) return stream;
53
+ if (encodings.length > MAX_CONTENT_ENCODINGS) throw new TypeError("Too many content encodings.");
54
+ let decompressedStream = stream;
55
+ for (let i = encodings.length - 1; i >= 0; i--) decompressedStream = decompressedStream.pipeThrough(new DecompressionStream(encodings[i]));
56
+ const fetchResponse = new Response(decompressedStream, { headers: toFetchHeaders(decompressedHeaders) });
57
+ return toStandardBody(fetchResponse, { hint });
58
+ }
59
+ };
60
+ };
61
+ return {
62
+ ...options,
63
+ transportInterceptors: [...toArray(options.transportInterceptors), transportInterceptor]
64
+ };
65
+ }
66
+ };
67
+ export { ResponseCompressionLinkPlugin };